获取可滚动div中的第一个和最后一个可见元素

我有一个可滚动的div中的拇指列表,使用next / prev按钮进行动画制作。 每次单击“下一步”按钮都应与第一个可见元素的属性匹配。 每次点击“上一步”按钮都应该给我最后一个可见元素的属性。

我真的不知道如何在数学上解决这个问题,因为滚动距离在列表结束时是可变的。 有人可以帮帮我吗?

HTML

$
  • ...

jQuery的

 $('a.next').click(function() { var scrollheight = $("#scrollContent").scrollTop(); $("#scrollContent").animate({scrollTop:scrollheight+375},500,function() { // get "data-asset-id" of first visible element in viewport }); }); $('a.prev').click(function() { var scrollheight = $("#scrollContent").scrollTop(); $("#scrollContent").animate({scrollTop:scrollheight-375},500,function() { // get "data-asset-id" of last visible element in viewport }); }); 

看看小提琴: http : //jsfiddle.net/desCodLov/77xjD/10/

谢谢。

这是你在找什么? :

 var first, last; $('a.next').click(function() { var scrollheight = $("#scrollContent").scrollTop(); $("#scrollContent").animate({scrollTop:scrollheight+375},500,function() { $("#assetList li").each(function() { if ($(this).offset().top == 1 && $(this).offset().left == 0) { first = $(this).attr('data-asset-id'); } }); }); }); $('a.prev').click(function() { var scrollheight = $("#scrollContent").scrollTop(); $("#scrollContent").animate({scrollTop:scrollheight-375},500,function() { var Otop = $("#scrollContent").height() - $("#assetList li").height() - parseInt($("#assetList li").css('margin-top')); var Oleft = ($("#assetList li").width() + parseInt($("#assetList li").css('margin-right'))) * 3; $("#assetList li").each(function() { if ($(this).offset().top == Otop && $(this).offset().left == Oleft) { last = $(this).attr('data-asset-id'); } }); }); }); 

小提琴: http : //jsfiddle.net/77xjD/17/

通过可见性,我认为该元素至少应该可以看到右上角。 如果只想选择完全可见的元素,请添加或减去元素的width()height()值。 基本代码如下所示:

 var $first, $last, $container = $("#assetList"), $items = $container.children("li"), positions = container.offset(), rightside = positions.left + $container.width(), bottomside = positions.top + $container.height(); $items.each(function(){ var $this = $(this), position = $this.offset(); // If 
  • top post >=
      top if ($first && position.top >= positions.top // If
    • left >=
        left && positions.left >= position.left) { /* Optionally, add two more conditions, to only accept elememts which are fully visible: && positions.top + $this.height() <= bottomside && positions.left + $this.width() <= leftside */ $first = this; } // See previous comments. if (position.top < bottomside && position.left < rightside) { $last = this; } }); // $first = first visible element, eg [HTMLLiElement] // $last = last visible element, eg [HTMLLiElement]
  • 我刚刚在你的小提琴中更新了解决方案。

    我在初始化时缓存了第一个li的顶部和最后一个li的顶部位置,并使用它们找出当你点击下一个或上一个按钮时哪个元素正在获取位置。

    当然我从Rob W的回答中复制了以下几行。

     var $container = $("#assetList"), $items = $container.children("li"),