【问题标题】:How can i add the offset with window.location.hash如何使用 window.location.hash 添加偏移量
【发布时间】:2014-05-29 17:20:21
【问题描述】:

我用这个功能。

window.location.hash = "Home"

我想要做的是,当锚点进入 id 为 Home 的 div 时,我希望 div 的顶部位置比实际开始的 div 高一点。

谁能帮我在 div 开始的地方添加一个偏移量,例如 20px。

谢谢

【问题讨论】:

  • window.location.hash<div>的位置是什么关系?
  • 你不能给 DIV 添加一些填充吗?
  • 使用函数 window.location.hash 我可以使用 jquery 跳转到 id 为 Home 的 div,但我想要的是跳转到浏览器顶部边框之间有间隙的 div和div。我不能使用填充,因为我制作的是单页设计模板

标签: jquery html hash


【解决方案1】:

你可以试试offsetTop

一个简单的例子:

$(document).ready(function(){
    $('a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();
      
        var target = this.hash,
        $target = $(target);
      
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top-40
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

注意$target.offset().top-40

这意味着它将重定向到带有margin-top: -40px的div。

【讨论】:

  • 也许你也可以将它绑定到 onhashchange 事件,这取决于 OP 正在寻找什么。无论如何,+1
  • 我只是展示一个非常基本的例子。我们没有看到 OP 的完整代码,所以这个基本示例应该足够了。
  • 是的,我完全同意
  • 该演示正是我使用的,但我也使用的是,如果我只是向下滚动,如何更改锚点?
  • 什么意思?你能发布你的整个代码吗?
猜你喜欢
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2011-07-25
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
相关资源
最近更新 更多