Jquery scrollTop 在 Firefox 中无法正常工作
Jquery scrollTop not working as it should in Firefox
我正在构建一个单页网站,它使用 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。
有没有办法在不影响其他浏览器的情况下解决这个问题?
上找到网站预览
编辑我做了一个屏幕截图来澄清问题,你可以在这个link上看到它:http://kiranvanursel.tinytake.com/sf/MTYxMTg5XzEwMTM1Njk
似乎 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 属性中裁剪哈希应该适用于所有浏览器。
也许 'jump' 是设置 window.location.hash
的结果。
尝试使用 html5 pushstate 事件更新 url。我已经更新了代码块,我认为值得一试
我正在构建一个单页网站,它使用 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。 有没有办法在不影响其他浏览器的情况下解决这个问题?
上找到网站预览编辑我做了一个屏幕截图来澄清问题,你可以在这个link上看到它:http://kiranvanursel.tinytake.com/sf/MTYxMTg5XzEwMTM1Njk
似乎 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 属性中裁剪哈希应该适用于所有浏览器。
也许 'jump' 是设置 window.location.hash
的结果。
尝试使用 html5 pushstate 事件更新 url。我已经更新了代码块,我认为值得一试