我有一个带有重复元素的全宽div。溢出时,我隐藏了溢出的内容,并且不显示空白。我的问题是我想计算隐藏项目的数量(或我猜的显示项目),但无法弄清楚如何。
您可以在https://codepen.io/joshuaohana/pen/aqPJMr
查看此基本示例在这种情况下,控制隐藏的css是
div {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
white-space: nowrap;
overflow: hidden;
}
如果你删除溢出线,你会得到一个滚动条,把它放回去,没有滚动条。
当溢出设置为隐藏时,我需要的是一种计算隐藏在丢失溢出部分中的项目的方法。
我发现的唯一事情是试图计算隐藏了哪些元素,但这并不适用于溢出项目。我无法找到可以搜索的任何不同的限定词。
答案 0 :(得分:2)
这是一种使用jQuery的方法。检测包含div
的宽度。然后使用offset()
方法计算{width}超出此宽度的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>