栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使锚链接在其链接位置上方一些像素

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使锚链接在其链接位置上方一些像素

window.addEventListener(“hashchange”, function () {
window.scrollTo(window.scrollX, window.scrollY - 100);
});

这将允许浏览器为我们完成跳转到锚点的工作,然后我们将使用该位置进行偏移。

编辑1:

正如@erb指出的那样,仅当您在页面上更改哈希值时,此方法才有效。输入

#something
网址中已经存在的页面不适用于上述代码。这是处理该问题的另一个版本:

// The function actually applying the offsetfunction offsetAnchor() {    if(location.hash.length !== 0) {        window.scrollTo(window.scrollX, window.scrollY - 100);    }}// This will capture hash changes while on the pagewindow.addEventListener("hashchange", offsetAnchor);// This is here so that when you enter the page with a hash,// it can provide the offset in that case too. Having a timeout// seems necessary to allow the browser to jump to the anchor first.window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).

注意:要使用jQuery,您只需 在示例中将替换

window.addEventListener
$(window).on
。谢谢@Neon。

编辑2:

如少数人所指出的,如果您连续两次单击同一锚点链接,则以上操作将失败,因为没有

hashchange
事件会强制偏移。

此解决方案是@Mave的建议的非常轻微的修改版本,并使用jQuery选择器进行简化

// The function actually applying the offsetfunction offsetAnchor() {  if (location.hash.length !== 0) {    window.scrollTo(window.scrollX, window.scrollY - 100);  }}// Captures click events of all <a> elements with href starting with #$(document).on('click', 'a[href^="#"]', function(event) {  // Click events are captured before hashchanges. Timeout  // causes offsetAnchor to be called after the page jump.  window.setTimeout(function() {    offsetAnchor();  }, 0);});// Set the offset when entering page with hash present in the urlwindow.setTimeout(offsetAnchor, 0);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/623887.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号