问题描述
我正在寻找一个页面上所有DOM元素的已使用css值。当我说使用值时,指的是:
>这些应是根据实际页面布局计算的最终值。 声称您可以使用 window.getComputedStyle
获取使用的值,但这对我没有意义,因为计算的值不同于使用的值(和我想要使用的值)。即使这些是使用的值,我不知道这是否只在Firefox中工作。有没有办法可靠地在所有浏览器中使用值?
我相信 会返回used根据该定义。它适用于所有主要的现代浏览器。早期版本的IE以。请注意定义的最后一个句子:
/ em>例如,此代码显示500px或类似,而不是50%。例如, :
HTML:
< div id =target style =display:inline-block; width:50%> x< / div>
JavaScript:
code>(function(){
var target = document.getElementById(target);
var style = window.getComputedStyle(target);
display calculate width =+ style.width);
函数显示(msg){
var p = document.createElement('p');
p.innerHTML = String (msg);
document.body.appendChild(p);
}
})();
|
I'm looking to get the used css values of all DOM elements on a page. When I say "used values" I'm referring to the definition as specified in the W3C specification:
These should be the final values computed with respect to the actual page layout. Mozilla's docs claim that you can use window.getComputedStyle
to get the used values, but this does not make sense to me because computed values are different from used values (and I want used values). Even if these are the used values, I'm not sure if this only works in Firefox or not. Is there a way to reliably get used values in all browsers?
I believe getComputedStyle
does return "used" values according to that definition. It works on all major modern browsers. Earlier versions of IE provide a near-equivalent in the form of currentStyle
. Note the last sentence of the definition:
(My emphasis at the end.) E.g., the "used value" is the value that is actually used.
For example, this code shows me "500px" or similar, not "50%":
HTML:
<div id="target" style="display: inline-block; width: 50%">x</div>
JavaScript:
(function() {
var target = document.getElementById("target");
var style = window.getComputedStyle(target);
display("computed width = " + style.width);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
这篇关于是否有跨浏览器的方法来获取所有元素的所有属性的css值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!