向1个方向滚动时的回调函数

时间:2013-02-28 22:09:58

标签: jquery

当我向右滚动300px时,如何获得回调?

<div id="container">

    <div class="scrollable">
        this will be 6000px wide
    </div>

</div>

CSS

#container {width: 900px; overflow: hidden;}
.scrollable {width: 6000px; overflow-x: scroll;}

js(随意重写,我只是试着这个例子)

$('#container').scroll(function (evt) {
    var target = $(evt.currentTarget);
    horizontal_scroll = target.scrollLeft();
    if (previous_scroll < horizontal_scroll && horizontal_scroll % 100 == 0) {
        previous_scroll = horizontal_scroll;
        alert("You've scrolled 300px to the right");
    }

});

1 个答案:

答案 0 :(得分:0)

您可以使用jQuery的$.offset()方法确定内部div移动了多远,并在超过-300px(负数)时发出警报:

var alerted = false; // prevents unlimited alerts
$('#container').on('scroll', function(e){
    var el = $(this),
        os = $('.scrollable',this).offset();

    if (os.left <= -300 && alerted !== true){
        alert('Scrolled 300px');
        alerted = true; // prevent unlimited alerts
    }
});

此处更新了小提琴:http://jsfiddle.net/4upYj/

我希望这有帮助!