简体   繁体   English

JavaScript中的自动表格布局策略?

[英]Auto Table Layout Strategy in JavaScript?

Mozilla have their auto table layout algorithm available: Mozilla提供了自动表格布局算法:

https://developer.mozilla.org/en/docs/Table_Layout_Strategy https://developer.mozilla.org/en/docs/Table_Layout_Strategy

Has anyone ever seen a similar implementation in a JavaScript library? 有没有人在JavaScript库中看到过类似的实现?

What I'm wanting to do is take tabular JSON data and calculate appropriate column widths in a similar manner to what HTML's auto table layout is doing. 我想要做的是采用表格JSON数据,并以与HTML自动表布局相似的方式计算适当的列宽。 I'm not interested in tricks like letting the browser do the layout, then looking at widths etc, I'm wanting to perform the calculation in JS from raw data. 我对让浏览器进行布局,然后查看宽度等技巧不感兴趣,我想根据原始数据在JS中执行计算。

You cannot measure the width of text content without first rendering it to screen (because you have to contend with different screen resolutions, user font settings, etc etc etc). 您必须先将文本内容呈现到屏幕上才能测量文本内容的宽度(因为您必须应对不同的屏幕分辨率,用户字体设置等)。

There is one exception though, but its not entirely accurate. 虽然有一个例外,但是它并不完全准确。 The canvas element has the ability to measure text dimensions , but in my experience it isn't precisely accurate and thusly not worth the trouble/overhead of pre-rendering all of your content to get a less-than-accurate reading. canvas元素具有测量文本尺寸的能力,但是根据我的经验,它不是精确准确的,因此不值得为呈现不准确的内容而预先渲染所有内容的麻烦/开销。

Some other cheap tricks involve explicitly setting the size and font of the content to a predictable-width-mono-spaced-character-font and then counting the number of characters in the string...but that falls apart quickly in scenarios where the content line-feeds/wraps to fit inside a container. 其他一些便宜的技巧包括将内容的大小和字体显式设置为可预测的宽度,等距字符字体,然后计算字符串中的字符数...但是在内容出现错误的情况下,这种方法会很快瓦解换行/自动换行以适合容器内部。 You could also "pre-render" your text into a hidden container in the DOM (think display: hidden or z-index:-999) and get a container measurement that way, but more often than not that devolves into a ton of per-column logic that becomes unwieldy a few requirement changes down the road. 您还可以将文本“预呈现”到DOM中的隐藏容器中(认为显示为:隐藏或z-index:-999),并以此方式进行容器度量,但更多情况下会降低成笨拙的一些要求的-列逻辑一直在改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM