向下滚动页面时,jQuery 使 div 滑入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15026466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:15:01  来源:igfitidea点击:

jQuery make div slide in when scrolling down page

jqueryhtmlscrolljquery-animate

提问by Sam Skirrow

I want to make a div slide onto my page from the right when a user scrolls down the page (the div will contain a link that takes them back to the top of the page). Here is the code I'm currently using:

当用户向下滚动页面时,我想让一个 div 从右侧滑到我的页面上(该 div 将包含一个将它们带回页面顶部的链接)。这是我目前使用的代码:

jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > 100) {
    jQuery('.totop').animate({ right: '0px' });
} else {
    jQuery('.totop').animate({ right: '-300px' });
}
});

And the CSS:

和 CSS:

.totop {
position:fixed;
bottom:50%;
right:-300px;
width:300px;
height:100px;
font-size:30px;
color:white;
background:#f18500;
}

The Div is behaving very oddly, when I scroll down the div takes about 5 seconds to appear, then it comes into view but looks like it is making several attempts to slide off again before remaining still, when I slide back to the top it dissapears...but after about 5 seconds again. Would love some help to find out what is wrong with my code please.

Div 的行为非常奇怪,当我向下滚动 div 需要大约 5 秒才能出现,然后它进入视图但看起来它在保持静止之前再次尝试滑落,当我滑回顶部时它消失了...但又过了大约 5 秒。希望得到一些帮助,以找出我的代码有什么问题。

回答by iappwebdev

Your animations are getting queued, use .stop():

您的动画正在排队,请使用.stop()

jQuery(window).scroll(function () {
    if (jQuery(this).scrollTop() > 100) {
        if (jQuery('.totop').hasClass('visible') == false) {
            jQuery('.totop').stop().animate({
                right: '0px'
            }, function () {
                jQuery('.totop').addClass('visible')
            });
        }
    } else {
        if (jQuery('.totop').hasClass('visible') == true) {
            jQuery('.totop').stop().animate({
                right: '-300px'
            }, function () {
                jQuery('.totop').removeClass('visible')
            });
        }
    }
});

DEMO: http://jsfiddle.net/MkJwm/

演示:http: //jsfiddle.net/MkJwm/

回答by 0_0

Something like this:

像这样的东西:

$(window).scroll(function(){
    if ($(this).scrollTop() > 50) {
        $('#div-to-show').slideDown('slow');
    } else {
        $('#div-to-show').slideUp('slow');
    }
});

Not tested.

未测试。