如何在 Javascript 中获取 css3 多列计数
我们使用新的 css3 多栏布局属性将文本放入报纸栏目中。每列都有固定的宽度,列数默认为“auto”,这意味着浏览器决定有多少列。
我们如何在 Javascript 中获取整数的实际列数?
如果我们查询 css“column-count”(或 -moz-column-count),我们会得到“auto”或空白结果。
We're using the new css3 multi-column layout properties to get our text into newspaper columns. Each column gets a fixed width, and the column-count defaults to "auto", which means that the browser decides how many columns there are.
How do we get the actual number of columns as an integer in Javascript?
If we query the css "column-count" (or -moz-column-count) we get either "auto" or a blank as a result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
秘诀是在内容末尾放一个小标记。您可以以编程方式添加一个空范围:
然后使用 jquery $("#mymarker") 获取该范围并获取“left”属性。将该数字除以列的宽度(根据列间隙进行调整),这将告诉您最后一个元素位于哪一列。对该值进行 Math.ceil() ,您就可以得到列数。
The secret is to put a small marker at the end of the content. You can programmatically add an empty span:
then grab the span using a jquery $("#mymarker") and get the "left" property. Divide that number by the width of the columns (adjusted for column-gap), and that will tell you what column this last element is in. Math.ceil() on the value and you have the column count.
将列容器的
可滚动宽度
除以可见宽度
:Divide the column container's
scrollable width
byvisible width
:试试这个:
代码说明:
此代码将为每个 jQuery 元素创建一个函数“howMuchCols”。
您无法使用常规方式获取具有列的元素的宽度,因为他的宽度用于定义每个内部列的大小。要知道元素内部有多少列,您需要获取其实际宽度并除以列大小,然后就可以得到列数。
获得真实宽度的方法是将列容器的最后一个子元素的 X 偏移量与其宽度相加,然后减去列容器的 X 偏移量之和。
在代码中,我在减法和除法之后添加了一列的大小,而不是在除法之前使用像素单位(它没有区别)。
Math.round 必须存在,因为容器大小并不总是能被其内部列宽度整除。
Try this:
Code explanation:
This code will create a function 'howMuchCols ' to each jQuery element.
You can't get the width of a element with columns using the conventional way, because his width is used to define each inner column size. To know how many columns the element have inside, you need to get his real width and divide by the columns size, then you will have the column amount.
The way to get the real width is to sum the X offset of the last child element of the columns container with it width, then, subtract it with the sum of the column container X offset.
In the code, I have added the size of one column after make the subtraction and division rather than use the pixel unit before the division (it does not make difference).
The Math.round must be there because not always the container size will be exactly divisible by his inner columns width.
您可以为每一列设置一个类,例如 class="another-column",然后使用 Jquery 选择类并迭代它们。
警告,这未经测试。如果你可以提供一些 html/css3 代码我可以在 jsfiddle 上测试它
could you set a class to each column such as class="another-column" and then use Jquery to select the classes and iterate them.
Warning, this is untested. If you could supply with some html/css3 code I could test it on jsfiddle