2013-02-28 60 views
0

當我滾動到右側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"); 
    } 

}); 

回答

0

您可以使用jQuery的$.offset()方法來確定多遠內div已移動,並且一旦超過-300像素(負值)就會發出警報,如下所示:

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/

我希望這有助於!