简体   繁体   English

使用jQuery在水平方向上滑动DIV

[英]Sliding DIV in horizontally with jQuery

I'm sliding a DIV into the viewport horizontally after a user has scrolled down (x) pixels. 在用户向下滚动(x)像素后,我将DIV水平滑动到视口中。 It then scrolls out again if they scroll back up. 如果它们向上滚动,它会再次向外滚动。 However the way it slides seems to be very very jerky (it pauses at moments too). 然而它滑动的方式似乎非常非常生涩(它暂时停顿)。

<div id="doom_o"></div>
div#doom_o {
    position: fixed;
    left: -300px;
    z-index: -1;
    height: 400px;
    width: 309px;
    background-image: url("../images/doom_o.png");
    background-repeat: no-repeat;
}
$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        setTimeout(function() {
            $('#doom_o').stop().animate({left: "20%"});
        }, 250);
    } 
    else {
        setTimeout(function() {
            $('#doom_o').stop().animate({left: "-300px"});
        }, 250);
    }
});

You need to remove the setTimeout calls from the if condition and then put the whole block into it's own setTimeout . 您需要从if条件中删除setTimeout调用,然后将整个块放入它自己的setTimeout This will mean that the code is only run once as the scrolling finishes, rather than every time the scroll event fires which is what causes the stuttering. 这意味着代码只在滚动完成时运行一次,而不是每次滚动事件触发时都会导致口吃。

var timer;
$(window).scroll(function() {
    clearTimeout(timer);
    var timer = setTimeout(function() {
        if ($(this).scrollTop() > 100) {
            $('#doom_o').stop().animate({ left: "20%" });
        } 
        else {
            $('#doom_o').stop().animate({ left: "-300px" });
        }
    }, 150)
});

Example fiddle 示例小提琴

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

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