尝试编写一个脚本来为解析到当前页面上的 anchor 的所有链接添加平滑滚动。尝试使其通用,以便它在整个站点范围内工作。
var links = document.querySelectorAll('a')
var anchorLinks = []
for (var i = 0; i < links.length; i += 1) {
console.log(links[i].href, window.location.href)
}
这就是我的开始,但我遇到了挑战,我正在 Stackoverflow 上联系,看看是否有人在没有 jQuery 的情况下完成了这项工作。
我必须检查 href 是否有 #
,但我还必须检查当前 URL 是否与 href 匹配,因为其他网站也使用 #
.
这样可以吗?还是我还漏掉了其他东西?
最佳答案
总结一下,请参阅Location object .
试试这个:
var links = document.querySelectorAll('a')
var anchorLinks = [].filter.call(links,a=>(
a.host==window.location.host&&
a.pathname==window.location.pathname&&
a.search==window.location.search&&
a.hash!=window.location.hash))
实际上还有另一种方法可以做到这一点:
var locwohash = window.location.href.replace(/#.+/, "")
var anchorLinks = document.querySelectorAll('a[href^="'+locwohash+'"],a[href^="#"]')
应该更快,但如果想要对不同类型的链接 href 具有鲁棒性,则会很复杂。 (对于http://example.com/path/to/page#hash
,此页面中有许多链接到 anchor 的href,#another-hash
,page#another-hash
,example.com/path/to/page#another-hash
,/path/to/page#another-hash
,//example.com/path/to/page#another-hash
,http://example.com/path/to/page#another-hash
,全部其中的选择器是等效的但不相同。
关于javascript - 如何为页面中的所有 anchor 链接添加平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45704060/