如何选择容器中的可见元素?

时间:2017-02-09 13:51:28

标签: jquery html css

我有div .wrapper,其中包含ul个小短语li列表。

divwidth:600pxheight:20pxoverflow:hidden

我想只选择div中的可见短语并为其添加一个类。

怎么做?

.wrapper {
  background: #eee none repeat scroll 0 0;
  border: 1px solid #ddd;
  height: 20px;
  overflow: hidden;
  padding: 5px;
  width: 600px;
  float: left;
}
ul {
  float: left;
  margin: 0;
  padding: 0;
}
ul li {
  float: left;
  padding: 0 5px;
  list-style-type: none;
}
<div class="wrapper">
  <ul>
    <li><a>Vocabulary Bowl.</a>
    </li>
    <li><a>Bowl.</a>
    </li>
    <li><a>Today's Leaders.</a>
    </li>
    <li><a>Weekly LeadersToday's.</a>
    </li>
    <li><a>Bowl.</a>
    </li>
    <li><a>Monthly Leaders.</a>
    </li>
    <li><a>Bowl.</a>
    </li>
    <li><a>Vocabulary Bowl Today's Leaders.</a>
    </li>
    <li><a>Bowl Leaders.</a>
    </li>
    <li><a>Today's Leaders Today's Leaders Today's Leaders.</a>
    </li>
    <li><a>Weekly Leaders.</a>
    </li>
    <li><a>Monthly.</a>
    </li>
    <li><a>Vocabulary Bowl.</a>
    </li>
    <li><a>Bowl Leaders.</a>
    </li>
    <li><a>Today's Leaders.</a>
    </li>
    <li><a>Weekly Leaders.</a>
    </li>
    <li><a>Monthly Leaders.</a>
    </li>
    <li><a>Vocabulary Bowl.</a>
    </li>
    <li><a>Bowl Leaders.</a>
    </li>
    <li><a>Today's Leaders.</a>
    </li>
    <li><a>Weekly Leaders.</a>
    </li>
    <li><a>Monthly Leaders.</a>
    </li>
  </ul>
</div>

3 个答案:

答案 0 :(得分:2)

您需要检查视口中是否显示li

function isElementInViewport(el) {
    var rect = el.getBoundingClientRect();

    return rect.bottom > 0 &&
        rect.right > 0 &&
        rect.left < (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ &&
        rect.top < (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */;
}

$("li").forEach(li => {
  if(isElementInViewport(li) {
    //li is visible in the viewport
  })
})

答案 1 :(得分:0)

您可以将每个子矩形(boundingClientRect)与包装器的矩形进行比较。

https://jsfiddle.net/wbramLm4/2/

var wrapper = document.querySelector('.wrapper'), 
    wrapperBox = wrapper.getBoundingClientRect();

  // the elements that are at least partially visible: top left corner fits in the wrapper
  var inBoxPartial = $("li").filter( function(idx, li){
    var liBox = li.getBoundingClientRect();
    return liBox.top < wrapperBox.bottom && liBox.left < wrapperBox.right;
  });

  // the elements that are completely visible: bottom right corner in the wrapper      
  var inBoxTotal = $("li").filter( function(idx, li){
    var liBox = li.getBoundingClientRect();
    return liBox.bottom < wrapperBox.bottom && liBox.right < wrapperBox.right;
  });
  console.log( inBoxPartial, inBoxTotal );

答案 2 :(得分:0)

我通过比较短语的总宽度和class =&#34; wrapper&#34;的宽度来判断它。 我用jQuery编写这些代码。

$(document).ready(function(){
    var len=0;
    $("li").each(function(e){
        len+=$(this).width();
        if(len>$(".wrapper").width())
            $(this).addClass("hide");
    })
})