Scrollable Div, which elements can be seen

后端 未结 4 1525
情话喂你
情话喂你 2021-02-06 14:51

We have a scrollable div that has CSS hieght:40px;. Inside it are multiple LI height:20px

    
  • 4条回答
    •  忘了有多久
      2021-02-06 15:02

      jQuery's position method gets the position relative to the container, and you can get the top position by doing $("li").position().top;

      So my solution was to write a loop to go through all the elements and find the one with the smallest value for position().top and pick that out. Here's the script I wrote:

      $(function() {
      
          var mostVisibleItem = $("li:first");
      
          var smallestOffset = mostVisibleItem.position().top;
          $("li").each(function(i, item) {
              if($(item).position().top < smallestOffset)
              {
                  smallestOffset = $(item).position().top;
                  mostVisibleItem = $(item);
              }
          });
          mostVisibleItem.css("color", "red");
      });
      

      You can see this working in JSFiddle here: http://jsfiddle.net/P69y2/

      Hope this helps :)

    提交回复
    热议问题