offset()。top -XX在Webkit v Firefox / IE中给出了不同的结果

时间:2015-02-25 00:27:03

标签: javascript jquery firefox scroll webkit

我试图在具有固定标题的网站上实现平滑滚动到内部锚点。

如果我这样做:

scrollTop: $target.offset().top

我在所有浏览器中获得相同的结果,但如果我这样做:

scrollTop: $target.offset().top - 100
在Webkit浏览器中它很好,但在Firefox和IE中,滚动到锚点后,页面会进一步猛烈抬起,因此标题下的标题会变得模糊。

剧本:

$('[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
      scrollTop: $target.offset().top - 100
    }, 900, 'swing', function () {
      window.location.hash = target;
    });
});

CodePen

1 个答案:

答案 0 :(得分:0)

我通过向目标添加padding-top找到了一种解决方法。