Jquery scrollTop在Firefox中不能正常工作

时间:2015-05-19 09:41:40

标签: jquery firefox scrolltop

我正在构建一个使用Jquery的scrollTop()函数的单页网站。

这是我的代码:

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

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

它适用于Chrome,Safari en Vivaldi,但是当我在FireFox中运行该网站时,我的targetOffset并不需要。 有没有办法解决这个问题,而不影响其他浏览器?

可以在http://listycon.kiran.be

上找到该网站的预览

编辑我做了一个屏幕截图来澄清问题,你可以在这个链接上看到它:http://kiranvanursel.tinytake.com/sf/MTYxMTg5XzEwMTM1Njk

1 个答案:

答案 0 :(得分:2)

似乎firefox从你的a-tag中的href中获取.hash有些麻烦。 你可以尝试这些方面:

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) { 
        e.preventDefault();
        var href = $(this).attr('href');
        href = '#' + href.split('#').pop();

        var $target = $(href).offset().top - 140;

        $('html, body').animate({
            'scrollTop': $target
        }, 900, 'swing', function () { 
            window.history.pushState("object or string", "Title", href);
        });
    });
});    

从href属性中剪切哈希应该适用于每个浏览器。

也许是'跳跃'设置window.location.hash

的结果

尝试使用html5 pushstate事件更新网址。我已经更新了代码块,我认为值得一试

相关问题