抖动子元素'填充父元素的尺寸
假设我有一个宽度为 500px 的父 div。它有 13 个应填满其宽度的子元素。
如果我为每个子元素指定宽度 500 / 13 = 38.46... 像素,则浏览器将对像素值进行底线处理,因此最终会得到 13 个元素,总共占用 38 * 13 = 494 像素。父 div 右侧将有 6 个像素未填充。
是否有一种简单的方法来抖动子元素宽度,以便将剩余部分(6 像素)分布在一些子元素之间,从而使总宽度达到 500 像素?
如果我必须手动进行计算并且无法让浏览器来管理它,那么抖动 在这种情况下我可以使用算法吗?
编辑:澄清 - 我正在使用 JavaScript 在客户端进行这些计算。此外,父 div 的大小和子 div 的数量在运行时会发生变化;上面的数字只是一个例子。
Say I have a parent div with width 500px. It has 13 child elements that should fill its width.
If I give each child element a width of 500 / 13 = 38.46... pixels, the browser will floor the pixel values, so I end up with 13 elements that take up a total of 38 * 13 = 494 pixels. There will be 6 pixels on the right side of the parent div that are not filled.
Is there an easy way to dither the child element widths so that the remainder (6 pixels) is distributed among some of the child elements, resulting in a total width of 500 pixels?
If I have to do the calculations manually and there's no way to get the browser to manage it, what dithering algorithm might I use in this case?
EDIT: A clarification -- I'm doing these calculations on the client side using JavaScript. Also, the size of the parent div and the number of child divs vary at runtime; the figures above are just an example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议你自己用整数数学来做所有事情。然后,您可以计算不均匀的数量,然后决定如何将其分布在元素之间。我的假设是,分配额外像素的最不引人注目的方法是保持尽可能多的类似宽度元素彼此相邻。
一种方法是计算有多少个额外像素 N,然后从左边开始为每个 N 元素提供一个额外像素。如果您担心事物不居中,您可以将第一个额外像素分配给最左边的对象,将第二个额外像素分配给最右边的对象,将第三个额外像素分配给左边第二个对象,将第四个额外像素分配给第二个对象对,等等...这将在不同宽度的对象之间多一个边界,但比第一个算法更对称。
下面是一些代码,展示了如何从外向内将额外的像素放在末端元素上:
这是一个查看其实际效果的小提琴: http://jsfiddle.net/jfriend00/qpFtT/2/
I'd suggest you just do everything with integer math yourself. You can then calculate what the uneven amount is and then decide how you want to distribute it across the elements. My supposition is that the least noticeable way to distribute the extra pixels would be to keep as many like width elements next to each other as possible.
One way of doing that would to calculate how many extra pixels N you have and then just give each N elements starting from the left one extra pixel. If you were worried about things not being centered, you could allocate the first extra pixel to the far left object, the second extra pixel to the far right, the third extra pixel to the 2nd from left, the fourth extra pixel from the 2nd from right, etc... This would have one more boundary between dissimilar width objects, but be more symmetric than the first algorithm.
Here's some code that shows how one could put the extra pixels on the end elements from outside in:
And here's a fiddle to see it in action: http://jsfiddle.net/jfriend00/qpFtT/2/