通过overflow:hidden计算隐藏元素数量

4
我有一个宽度为100%的div,其中包含一个重复的元素。当内容溢出时,我隐藏了溢出的内容并不显示空格。我的问题是我想要计算隐藏的项目数量(或者我猜想是显示的项目),但是我无法弄清楚如何做到这一点。
您可以在https://codepen.io/joshuaohana/pen/aqPJMr看到一个基本示例。
在这种情况下,控制隐藏的CSS是:
div {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow: hidden;
}

如果您移除了溢出行,您将得到一个滚动条;而如果将其放回去,则没有滚动条。

我需要的是一种方法来计算在溢出部分被隐藏的项目数量,当 overflow 设置为 hidden 时。

我所发现的唯一事情就是尝试计算哪些元素已被隐藏,但这并不适用于溢出项。我找不到任何我可以针对搜索的不同限定符。


你会使用jQuery吗? - sol
@sol 是的,jQuery很好。 - Joshua Ohana
1个回答

5

这是一种使用jQuery的方法。检测包含

的宽度。然后使用offset()方法计算那些具有左坐标在该宽度之外的元素数量。

var parentContainerWidth = $("div").width();
var elementCount = $('span').filter(function() {
  return $(this).offset().left >= parentContainerWidth;
}).length;
alert(elementCount);
div {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow: hidden;
}

span {
  background: pink;
  margin: 2px;
  padding: 1rem;
  font-family: sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>here is an item 1</span>
  <span>here is an item 2</span>
  <span>here is an item 3</span>
  <span>here is an item 4</span>
  <span>here is an item 5</span>
  <span>here is an item 6</span>
  <span>here is an item 7</span>
  <span>here is an item 8</span>
  <span>here is an item 9</span>
  <span>here is an item 10</span>
  <span>here is an item 11</span>
  <span>here is an item 12</span>
  <span>here is an item 13</span>
  <span>here is an item 14</span>
  <span>here is an item 15</span>
  <span>here is an item 16</span>
  <span>here is an item 17</span>
  <span>here is an item 18</span>
  <span>here is an item 19</span>
  <span>here is an item 20</span>
  <span>here is an item 21</span>
  <span>here is an item 22</span>
  <span>here is an item 23</span>
  <span>here is an item 24</span>
</div>


我有一个类似的问题。我有一个包含多个<p>标签作为子元素的div。 - Gowthamss
我有一个类似的问题。我有一个包含多个<p>标签的div作为子元素。div { line-height: 1.5; max-height: calc(var(--line-height) * 3); overflow: hidden;},而子p标签具有如下css - p { display: inline-block; }。因此,任何无法设置在max-width中的子p标签都将溢出。现在,在这种情况下,我该如何计算隐藏或可见元素的数量。var(--line-height)是我定义的变量,等于1.8。 - Gowthamss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接