2014-06-20 3 views
1

J'ai besoin d'obtenir le premier élément qui est entièrement visible dans un DIV scrollable en utilisant jQuery. Je suis proche, mais quelque chose ne va pas.Comment obtenir le premier élément entièrement visible dans un élément qui a un défilement horizontal en utilisant jQuery?

Quelqu'un peut-il déceler le problème?

$('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

Répondre

1

$this.offset() retournera position relative au document (pas div avec le défilement), afin de vérifier la visibilité que vous devez comparer à div poste (défile pas à gauche)

$('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 
    } 
}); 

voici un exemple: http://jsfiddle.net/axwR7/2/

Questions connexes