eir*_*ios 11 html anchor routing angular hash-location-strategy
我正在使用Angular 6项目,我已禁用/删除了hash-location-strategy,它从URL中删除#.
由于此更改链接具有:
<li routerLinkActive="active">
<a [routerLink]="['/settings']">Contact Settings</a>
<ul class="child-link-sub">
<li>
<a href="#contactTypes">Contact Types</a>
</li>
</ul>
</li>
Run Code Online (Sandbox Code Playgroud)
不再工作它只是跳过当前组件URL并将#contactTypes放在localhost之后.
我找到了这个应该解决问题的链接
<a [routerLink]="['/settings/']" fragment="contactTypes" >Contact Types</a>
Run Code Online (Sandbox Code Playgroud)
它将#contactTypes放在URL的末尾,但它不会滚动到浏览器的顶部.
Mac*_*ado 16
Angular 6.1带有一个叫做anchorScrolling路由器模块的选项ExtraOptions.正如anchorScrolling定义所说:
配置路由器是否应该在url有片段时滚动到元素.
'disabled'- 什么都不做(默认).
'enabled'- 滚动到元素.此选项将来是默认选项.锚定滚动不会发生在'popstate'上.相反,我们恢复存储的位置或滚动到顶部.
你可以像这样使用它:
const routerOptions: ExtraOptions = {
useHash: false,
anchorScrolling: 'enabled',
// ...any other options you'd like to use
};
// then just import your RouterModule with these options
RouterModule.forRoot(MY_APP_ROUTES, routerOptions)
Run Code Online (Sandbox Code Playgroud)
Joe*_*eph 14
我正在寻找一个类似的解决方案,并尝试使用ngx-scroll-to包,发现它不能在最新版本的角度工作,所以决定调查其他选项,发现我们可以使用scrollIntoView
HTML代码:
<button (click)="scrollToElement(target)"></button>
<div #target>Your target</div>
Run Code Online (Sandbox Code Playgroud)
Ts码:
scrollToElement($element): void {
console.log($element);
$element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}
Run Code Online (Sandbox Code Playgroud)
小智 13
这对我有用(我正在使用 Angular 12.1.3):
在 HTML 模板上:
<a (click)="scrollTo('anchorId')">Scroll to another position</a>
Run Code Online (Sandbox Code Playgroud)
将要滚动到的元素的 id(不带主题标签符号#)传递给函数。
然后,在 Typescript 上,使用 .scrollIntoView使浏览器滚动到该元素的位置。
scrollTo(element: any): void {
(document.getElementById(element) as HTMLElement).scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}
Run Code Online (Sandbox Code Playgroud)
出于可访问性的原因,我必须在文档开头添加一个链接,以便使用屏幕阅读器向用户提供对内容的直接访问,从而跳过页面的某些部分从页面到页面重复。
因为我需要链接保持焦点(最好保持 href 属性),因为我实际上在 app-root 或任何组件之外(仍然解决方案在组件内工作),为此我使用了简单的旧时尚 html 和 javascript :
<a href="./#content"
onclick="event.preventDefault(); location.hash='content';"
class="content-shortcut"
title="Access page content directly"
i18n-title
aria-label="Access page content directly"
i18n-label>Access page content directly</a>
<style>
.content-shortcut {
position: absolute;
opacity: 0;
height: 0px;
font-size: 1px;
}
.content-shortcut:focus,
.content-shortcut:active {
position: relative;
opacity: 1;
height: auto;
font-size: 1em;
display: block;
color: black;
background: white;
}
</style>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28769 次 |
| 最近记录: |