动画 scrollTop 在 Firefox 中不起作用 [英] Animate scrollTop not working in firefox

查看:24
本文介绍了动画 scrollTop 在 Firefox 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个功能很好用.它将主体滚动到所需容器的偏移量

This function works fine. It scrolls the body to a desired container's offset

function scrolear(destino){
    var stop = $(destino).offset().top;
    var delay = 1000;
    $('body').animate({scrollTop: stop}, delay);
    return false;
}

但不是在 Firefox 中.为什么?

But not in Firefox. Why?

-编辑-

为了在接受的答案中处理 de double trigger,我建议在动画之前停止元素:

To handle de double trigger in the accepted answer, I suggest stoping the element before the animation:

$('body,html').stop(true,true).animate({scrollTop: stop}, delay);

推荐答案

Firefox 将溢出置于 html 级别,除非专门设计了不同的样式.

Firefox places the overflow at the html level, unless specifically styled to behave differently.

要让它在 Firefox 中工作,请使用

To get it to work in Firefox, use

$('body,html').animate( ... );

工作示例

CSS 解决方案是设置以下样式:

The CSS solution would be to set the following styles:

html { overflow: hidden; height: 100%; }
body { overflow: auto; height: 100%; }

我认为 JS 解决方案的侵入性最小.

I would assume that the JS solution would be least invasive.

更新

下面的很多讨论都集中在为两个元素的 scrollTop 设置动画会导致回调被调用两次的事实.已建议使用浏览器检测功能,但随后又被弃用,其中一些功能可以说是牵强附会.

A lot of the discussion below focuses on the fact that animating the scrollTop of two elements would cause the callback to be invoked twice. Browser-detection features have been suggested and subsequently deprecated, and some are arguably rather far-fetched.

如果回调是幂等的并且不需要大量计算能力,则触发两次可能完全没有问题.如果多次调用回调确实是一个问题,并且如果您想避免特征检测,则强制执行回调仅在回调中运行一次可能更直接:

If the callback is idempotent and doesn't require a lot of computing power, firing it twice may be a complete non-issue. If multiple invocations of the callback are truly an issue, and if you want to avoid feature-detection, it might be more straight-forward to enforce that the callback is only run once from within the callback:

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');
}));

这篇关于动画 scrollTop 在 Firefox 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆