简体   繁体   English

jQuery在窗口滚动上设置动画

[英]jQuery animate on window scroll

I want to slid a div on window scroll to bottom. 我想在窗口滚动到底部滑动一个div。 When document reach 800 (bottom) Div should scroll right 0 and less then 800 it should slid and hide. 当文档到达800(底部)Div时,应向右滚动0,然后向右滚动800,然后滑动并隐藏。

Problem is when scrolling to bottom div is sliding and showing but again when scrolling to top it doesn't slid and hide. 问题是滚动到底部div时滑动并显示,但是滚动到顶部div时它又不会滑动并隐藏。

This is my code 这是我的代码

$(document).scroll(function () { // remove "$"
    var s = $("#slidebox");
    var y = $(this).scrollTop();        
    if (y > 800) {
        s.animate({"right":"-450px"}, "slow");
    } else if (y < 800) {

        s.animate({"right":"0px"}, "slow");
    }
});

Basically i want is to hide and show (with a slid effect) div on document scroll to bottom. 基本上我想要的是在文档滚动到底部时隐藏和显示(具有滑动效果)div。

Check scrolling below jsfiddle. 检查jsfiddle下面的滚动。

jsfiddle 的jsfiddle

On one hand, user390....'s response is correct in that the height is calculated incorrectly. 一方面,user390 ....的响应是正确的,因为高度计算不正确。

On the other hand, the way animations work is that they queue up one after another, so sometimes the div doesn't slide in/away until everything else before it is done. 另一方面,动画的工作方式是使它们依次排队,因此有时div直到完成所有其他操作之后才滑入/滑出。 Using .stop() fixes the issue . 使用.stop() 可解决问题

var s = $("#slidebox");

$(document).scroll(function () { // remove "$"
    var y = $(this).scrollTop() + $(window).height();        
    console.log(y);
    if (y > 800) {
        s.stop().animate({"right":"-450px"}, "slow");
    } else {
        s.stop().animate({"right":"0px"}, "slow");
    }
});

Your problem is that the value you are using for your "Did I reach the bottom" if statement is wrong. 您的问题是,如果陈述错误,您正在使用“我是否触底”的值。

Here is the calculated value you should be using: 这是您应该使用的计算值:

$(document).scroll(function () { // remove "$"
    var s = $("#slidebox");
    var y = $(this).scrollTop();
    var bottom = jQuery(document).height() - jQuery(window).height();
    if (y >= bottom) {
        s.animate({"right":"-450px"}, "slow");
    } else {
        s.animate({"right":"0px"}, "slow");
    }
});

Plus, I'd also recommand you to use a .stop(true, true) on your animated element before triggering the "animate" function if you don't want people to mess around with it. 另外,如果您不希望别人弄乱它,我还建议您在动画元素上使用.stop(true,true),然后再触发“动画”功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM