滚动到页面上的元素,然后运行回调 [英] Scroll to element on page, and then run callback

查看:111
本文介绍了滚动到页面上的元素,然后运行回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery的 .animate 滚动到页面上的元素,然后执行回调。

I am trying to use jQuery's .animate to scroll to an element on a page, and then execute a callback.

搜索后,我找到了这个函数:

After searching around, I found this function:

function scrollToElement(selector, callback){
    var animation = {scrollTop: $(selector).offset().top};
    $('html,body').animate(animation, 'slow', 'swing', callback);
}

这正确滚动到'selector'定义的元素,但调用了回调两次(因为 $('html,body')包含2个元素。)

This correctly scrolls to the element defined by 'selector', but callback is called twice (because $('html,body') contains 2 elements).

我试过改变

$('html,body').animate

到:

$(document).animate

和:

$(window).animate

但是,这些都没有做任何事情。

but, neither of those do anything.

我也尝试将功能更改为:

I also tried changing the function to this:

$('html').animate(animation, 'slow', 'swing', function(){
    $('body').animate(animation, 'slow', 'swing', callback);
});

但是,这使浏览器运行第一个动画,然后是第二个,所以我等了两个在回调运行之前运行(我不想要那样)。

but, this made the browser run the 1st animation and then the 2nd, so I had wait for both to run before the callback was ran (I dont't want that).

我想出 $('body')。scrollTop( )仅适用于Chrome, $('html')。scrollTop()仅适用于Firefox。

I figured out that $('body').scrollTop() only works in Chrome, and $('html').scrollTop() only works in Firefox.

那么,有没有办法(无需下载jQuery插件)让我滚动到Chrome和Firefox中的特定元素(我不关心IE),并执行回调(一次)?

So, is there a way (without needing to download a jQuery plugin) for me to scroll to a specific element in both Chrome and Firefox (I don't care about IE), and have a callback executed (once)?

编辑

我做了一个粗略的修复一个布尔值来检查回调是否已经运行,如果是,则不要再次运行它。

I made a crude fix by making a boolean to check if the callback ran already, and if it was, don't run it again.

function scrollToElement(selector, callback){
    var animation = {scrollTop: $(selector).offset().top};
    var callback_running = false;
    $('html,body').animate(animation, 'slow', 'swing', function(){
        if(typeof callback == 'function' && !callback_running){
            callback_running = true;
            callback();
        }
    });
}


推荐答案

我认为这也应该有效

function scrollToElement(selector, callback){
    var animation = {scrollTop: $(selector).offset().top};
    $('html,body').animate(animation, 'slow', 'swing', function() {
        if (typeof callback == 'function') {
            callback();
        }
        callback = null;
    });
}

这篇关于滚动到页面上的元素,然后运行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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