【问题标题】:How to get the first entirely visible element within an element that has horizontal scrolling using jQuery?如何使用 jQuery 在具有水平滚动的元素中获取第一个完全可见的元素?
【发布时间】:2014-06-20 19:49:43
【问题描述】:

我需要使用 jQuery 获取在可滚动 DIV 中完全可见的第一个元素。我很接近,但有些地方不对劲。

谁能发现问题?

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

【问题讨论】:

    标签: javascript jquery horizontal-scrolling


    【解决方案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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多