这个函数工作正常。它将主体滚动到所需容器的偏移量
function scrolear(destino){
var stop = $(destino).offset().top;
var delay = 1000;
$('body').animate({scrollTop: stop}, delay);
return false;
}
但在 Firefox 中没有。为什么?
-编辑-
为了处理已接受答案中的双重触发,我建议在动画之前停止元素:
$('body,html').stop(true,true).animate({scrollTop: stop}, delay);
最佳答案
Firefox 将溢出放置在 html
级别,除非专门设计为不同的行为。
要让它在 Firefox 中运行,请使用
$('body,html').animate( ... );
CSS 解决方案是设置以下样式:
html { overflow: hidden; height: 100%; }
body { overflow: auto; height: 100%; }
我认为 JS 解决方案的侵入性最小。
更新
下面的很多讨论都集中在这样一个事实,即为两个元素的 scrollTop
设置动画会导致回调被调用两次。浏览器检测功能已被建议并随后被弃用,有些可以说是牵强附会。
如果回调是幂等的并且不需要大量计算能力,则触发它两次可能完全不是问题。如果回调的多次调用确实是一个问题,并且如果您想避免功能检测,则强制回调仅在回调中运行一次可能更直接:
function runOnce(fn) {
var count = 0;
return function() {
if(++count == 1)
fn.apply(this, arguments);
};
};
$('body, html').animate({ scrollTop: stop }, delay, runOnce(function() {
console.log('scroll complete');
}));
关于jquery - 动画 scrollTop 在 firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8149155/