jQuery:在水平滚动上告诉哪个元素在viewport中

时间:2017-11-07 08:19:54

标签: javascript jquery scroll

我只找到垂直滚动类似问题的答案。

我在父div中有元素,这些元素具有相同的类,它们的父元素可以左右滚动。只有一个孩子可以完全看得见。我希望能够在滚动父项时告诉哪一个完全可见:

<div id="stickers">
    <div id="sticker-1" class="sticker"><img src="http://via.placeholder.com/320x200"></div>
    <div id="sticker-2" class="sticker"><img src="http://via.placeholder.com/320x200"></div>
    [...]
    <div id="sticker-8" class="sticker"><img src="http://via.placeholder.com/320x200"></div>
</div>


<script>
   var scrollingIsThrottled = false;
var sticker = $(".sticker");
 var window = $(window);


 $('#stickers').scroll(function() {
if (!scrollingIsThrottled) {
  scrollingIsThrottled = true;

  var StickerMatchingExpression = sticker.filter(function() {
    var $this = $(this);
    var left_of_element = $this.offset().left;
    var right_of_element = $this.offset().right;
    var bottomof = $('#stickers').height;
    var topof = $('#stickers').width;
    return ((bottomof > left_of_element) && (topof < right_of_element));
  });


  scrollingIsThrottled = false;
  }
});
</script>

1 个答案:

答案 0 :(得分:0)

假设#stickers有正确的CSS来进行溢出滚动(如果没有,你的滚动处理程序永远不会触发。)

var scrollingIsThrottled = false;
var sticker = $(".sticker");
$("#stickers").scroll(function() {
  var stickers_width = $(this).width();
  if (!scrollingIsThrottled) {
    scrollingIsThrottled = true;

    var StickerMatchingExpression = sticker.filter(function() {
      var $this = $(this);
      var left_of_element = $this.offset().left;
      var right_of_element = left_of_element + $this.width();
      return 0 <= left_of_element && right_of_element <= stickers_width;
    });
    scrollingIsThrottled = false;
  }
});