使用 CSS 或 JS 标记溢出 div 中最后一个可见的子级

Luk*_*uke 5 javascript css jquery jquery-selectors

我有一个带inline-blockdiv 的酒吧。其中一些在视口之外,因为我white-space:nowrap; overflow: hidden;为容器设置了:。我正在寻找选择最后一个可见孩子的方法。我所说的可见是指 div 被放置(最好是完全)在它的容器区域中。

据我所知,CSS 和 jQuery 中都没有这样的选择器。最接近的是 jQuery 的,:visible但它说所有的 div 都是可见的,因为它们占用了页面布局中的空间。

我看到的唯一出路是在加载和每次调整大小时枚举 div,以便通过求和其宽度、填充和边距来计算 div 是否仍在容器中。

您有更好的想法吗?

#container {
  white-space:nowrap;
  overflow: hidden;
}

.element {
  display: inline-block;
  vertical-align:top;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <div class="element">
    <img src="http://placehold.it/150x150" alt=""/>
  </div>
  <div class="element">
    <img src="http://placehold.it/150x150" alt=""/>
  </div>
  <div class="element">
    <img src="http://placehold.it/150x150" alt=""/>
  </div>
  <div class="element">
    <img src="http://placehold.it/150x150" alt=""/>
  </div>
  <div class="element">
    <img src="http://placehold.it/150x150" alt=""/>
  </div>
  <div class="element">
    <img src="http://placehold.it/150x150" alt=""/>
  </div>
  <div class="element">
    <img src="http://placehold.it/150x150" alt=""/>
  </div>
  <div class="element">
    <img src="http://placehold.it/150x150" alt=""/>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

在当前的非响应版本的堆栈溢出代码片段中,我们可以看到 4 个完整的 div 和第 5 个的一小部分。我想选择第五个(或者最好是第四个 div,因为下一个不完全可见)。

Luk*_*uke 0

这是我让它发挥作用的方法,但我欢迎任何更好的方法。

一切都由 jQuery 计算:

var cwidth = parseInt($('#container').width()); // get container width
var lastElement = $('#container .element:first'); // assume that first element is visible
$("#container .element:not(:first)").each(function(){
    //get right offset for every div
    var rightOffset = $(this).offset().left 
        + parseInt($(this).width())
        + parseInt($(this).css('padding-left'))
        + parseInt($(this).css('margin-left'));
    //if the right offset is bigger than container width then stop enumerating - previous one was the last fully visible
    if (rightOffset > cwidth){
        return false; 
    }
    //offset was lower than container with so this is our new fully visible element
    lastElement = $(this);
});

lastElement.addClass("lastvisible")
Run Code Online (Sandbox Code Playgroud)

优点:

  • 适用于不同的元素尺寸
  • 在窗口调整大小时添加相同的重新计算,您就得到了一种有效的响应方式

缺点:

  • 多次 jQuery 重新计算对浏览器来说非常重要
  • 在我看来丑陋的代码

https://jsfiddle.net/6k5xujtc/1/