1

在用户向下滚动 (x) 像素后,我将 DIV 水平滑动到视口中。如果他们向上滚动,它会再次滚动出去。然而,它滑动的方式似乎非常非常生涩(它也会暂停)。

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

1 回答 1

3

您需要setTimeout从条件中删除调用if,然后将整个块放入它自己的setTimeout. 这将意味着代码仅在滚动完成时运行一次,而不是每次触发滚动事件时都会运行,这就是导致卡顿的原因。

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

示例小提琴

于 2012-11-28T12:59:52.930 回答