javascript - 如何为页面中的所有 anchor 链接添加平滑滚动

标签 javascript

尝试编写一个脚本来为解析到当前页面上的 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-hashpage#another-hashexample.com/path/to/page#another-hash/path/to/page#another-hash//example.com/path/to/page#another-hashhttp://example.com/path/to/page#another-hash,全部其中的选择器是等效的但不相同。

关于javascript - 如何为页面中的所有 anchor 链接添加平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45704060/

相关文章:

javascript - 获取选定 SVG 元素的边界框

javascript - Dojo 将什么视为 XHR 请求错误?

javascript - 如何使用 ES6 代理 ArrayBuffer 或 Uint8Array?

javascript - 将表单数据写入 json 文件 - javascript

javascript - 检测点击窗口滚动条

javascript - 通过事件监听器打开/关闭传单图例

javascript - 无法在 JS 对象字面量方法中获取 dom 元素

javascript - 在 p5.js 中使用 random() 函数

javascript - 仅在验证检查和提交表单后显示模态

javascript - 当服务器关闭/崩溃时,Node JS 自动重启所有永远的 JS 进程