javascript - 通过 overflow hidden 统计隐藏元素的个数

标签 javascript css

我有一个带有重复元素的全宽 div。溢出时,我 overflow hidden 的内容并且不显示空白。我的问题是我想计算隐藏项(或我猜显示的项)的数量,但不知道如何计算。

您可以在 https://codepen.io/joshuaohana/pen/aqPJMr 上看到一个基本示例

在这种情况下,控制隐藏的 css 是

div {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow: hidden;
}

如果你删除溢出线你会得到一个滚动条,把它放回去,没有滚动条。

当溢出设置为隐藏时,我需要一种方法来计算丢失的溢出部分中隐藏的元素。

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

最佳答案

这是 jQuery 的一种方法。检测包含 div 的宽度。然后使用 offset() 方法计算 left 坐标超出此宽度的元素数。

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>

关于javascript - 通过 overflow hidden 统计隐藏元素的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49021065/

相关文章:

javascript - 确定数字位数的函数出错

javascript - 如何使用 JavaScript 获取从外部样式表派生的元素样式?

html - 不影响视口(viewport)大小的全宽横幅

CSS 帮助 - 如何通过响应式设计保持我的 div 就位

html - 如何将一个div置于另一个div中

javascript - 在 json get 中嵌套 ajax post

javascript - 如何使用 jquery 通过 ajax 单击指向 php 脚本的链接?

javascript - 如何从 WinJS 打开 .exe 文件

javascript - 使用 Express 运行服务器端 Javascript 版本

html - 将阴影和 z-index 应用于绝对定位元素