Angularjs 中的锚链接? [英] Anchor links in Angularjs?

查看:31
本文介绍了Angularjs 中的锚链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Angularjs 中使用锚链接?

Is it possible to use anchor links with Angularjs?

即:

 <a href="#top">Top</a>
 <a href="#middle">Middle</a>
 <a href="#bottom">Bottom</a>

 <div name="top"></div>
 ...
 <div name="middle"></div>
 ...
 <div name="bottom"></div>

谢谢

推荐答案

似乎有几种方法可以做到这一点.

There are a few ways to do this it seems.

Angular 提供了 $anchorScroll 服务,但文档严重缺乏,我无法让它工作.

Angular provides an $anchorScroll service, but the documentation is severely lacking and I've not been able to get it to work.

查看 http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html 深入了解 $anchorScroll.

我测试的另一种方法是创建自定义指令并使用 el.scrollIntoView().通过在您的指令链接函数中基本上执行以下操作,这可以很好地工作:

Another way I tested out was creating a custom directive and using el.scrollIntoView(). This works pretty decently by basically doing the following in your directive link function:

var el = document.getElementById(attrs.href);
el.scrollIntoView();

但是,当浏览器本身支持时,同时执行这两项操作似乎有点过分,对吗?

However, it seems a bit overblown to do both of these when the browser natively supports this, right?

如果您查看 http://docs.angularjs.org/guide/dev_guide.services.$location 及其 HTML 链接重写部分,您将看到以下链接没有被重写:

If you take a look at http://docs.angularjs.org/guide/dev_guide.services.$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:

包含目标元素的链接

示例:<a href="/ext/link?a=b" target="_self">link</a>

因此,您所要做的就是将 target 属性添加到您的链接中,如下所示:

So, all you have to do is add the target attribute to your links, like so:

<a href="#anchorLinkID" target="_self">Go to inpage section</a>

Angular 默认为浏览器,由于它是一个锚链接而不是不同的基本 url,浏览器会根据需要滚动到正确的位置.

Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.

我选择了选项 3,因为这里最好依赖本机浏览器功能,并节省我们的时间和精力.

I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.

必须注意,在成功滚动和哈希更改后,Angular 会跟进并将哈希重写为其自定义样式.但是,浏览器已经完成了它的工作,您可以开始使用了.

这篇关于Angularjs 中的锚链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆