2014-06-20 31 views
1

我需要使用jQuery獲得在可滾動DIV內完全可見的第一個元素。我很接近,但有些事情是不對的。如何獲得使用jQuery進行水平滾動的元素中的第一個完全可見的元素?

任何人都可以發現問題嗎?

$('div').on('scroll', function() { 
    var cutoff = $(this).scrollLeft(); 

    $('li').removeClass('firstVisible').each(function() { 
    var $this = $(this); 

    if ($this.offset().left > cutoff) { 
     $this.addClass('firstVisible'); 

     return false; // stops the iteration after the first one on the screen 
    } 
    }); 

    console.log($('li.firstVisible').index()); 
}); 

JSFiddle

回答

1

$this.offset()將相對位置返回到文檔(不帶滾動DIV),所以檢查的知名度,你需要把它比DIV位置(不是左滾動)

$('div').on('scroll', function() { 
var cutoff = $(this).offset().left; 

$('li').removeClass('firstVisible').each(function() { 
    var $this = $(this); 

    if ($this.offset().left >= cutoff) { 
     $this.addClass('firstVisible'); 

     return false; // stops the iteration after the first one on the screen 
    } 
}); 

這裏是一個例子:http://jsfiddle.net/axwR7/2/

相關問題