简体   繁体   English

如何获取元素的“指定”样式而不是计算样式

[英]How to get an element's “specified” style instead of computed style

On a web page that does not contain a viewport meta tag, most mobile browsers will "boost" some or all of the fonts on the page to a size larger than what the css specifies. 在不包含viewport元标记的网页上,大多数移动浏览器会将页面上的部分或全部字体“提升”到大于css指定的大小。 On mobile Safari, for instance, a specified size of 7px will be boosted to something like 12px . 例如,在移动Safari上,指定大小的7px将被提升到12px

You can read out the boosted value by using getComputedStyle . 您可以使用getComputedStyle读出提升值。 My question is, is there a reliable way to read out the unboosted value? 我的问题是,有没有一种可靠的方法可以读出未提升的价值? Ie if the font is boosted to 12, I want to know that it started out at 7. 即如果字体被提升到12,我想知道它从7开始。

Webkit has a deprecated function to get all stylesheet rules for an element: window.getMatchedCSSRules(<<element>>) . Webkit有一个不推荐使用的函数来获取元素的所有样式表规则: window.getMatchedCSSRules(<<element>>) You could use that to get the list of rules and loop through them to print or process the properties of each however you like. 您可以使用它来获取规则列表并循环遍历它们以打印或处理每个规则的属性。 You would also need to consider the style attribute of the element. 您还需要考虑元素的style属性。

To handle your font-size scenario, I imagine the best approach would be to get all the rules that apply to the element, order them by priority (remembering to factor in the style attribute and !important flags, and then pick out the value. 为了处理你的font-size场景,我想最好的方法是获得适用于元素的所有规则,按优先级排序它们(记住考虑style属性和!important标志,然后选择值。

This isn't exactly reliable though, since it's a Webkit function and it's on its way out. 但这并不完全可靠 ,因为它是一个Webkit函数,它正在逐渐消失。 There's a bunch of discussion here about how to fish out rules. 这里有一堆关于如何规避规则的讨论 Once you have the rules for an element, it's just a matter of picking out the specific information you need. 获得元素规则后,只需选择所需的特定信息即可。

Just a quick answer here. 这里只是一个快速的答案。 In short: you can't get specified styles with today's API's. 简而言之:您无法使用今天的API获得指定的样式。 I was able to solve my specific problem by temporarily turning off font-boosting by using text-size-adjust (prefixed with -webkit- for Safari). 能够暂时关闭使用的字体,提高解决我的特定问题的文字大小调整 (用-webkit-前缀的Safari浏览器)。

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

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