我正在构建一个使用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://kiranvanursel.tinytake.com/sf/MTYxMTg5XzEwMTM1Njk
答案 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事件更新网址。我已经更新了代码块,我认为值得一试