getComputedStyle

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了getComputedStyle相关的知识,希望对你有一定的参考价值。

function getStyle(elem, property) {
            // ie通过currentStyle来获取元素的样式,其他浏览器通过getComputedStyle来获取
            //svar that = this;
            return document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(elem,false)[property] : elem.currentStyle[property];
        }
var div1=document.getElementById("#div1");
		console.log(div1);
		console.log(getStyle(div1,‘width‘));

代码在运行的时候报出错误,

Uncaught TypeError: Failed to execute ‘getComputedStyle‘ on ‘Window‘: parameter 1 is not of type ‘Element‘.
    at getStyle (ts1.html:37)
    at

起初以为是getComputedStyle的使用方面出现了问题,了解一些知识后,并没有错误。这时,再看报出的错误信息提示,“无法解析Window上的getComputedStyle:参数1不是element类型”,这时尝试console.log("div1"),果然是null.于是去查了getElementById的用法,果然,是因为在参数里面多添加了一个#,去掉#,一切正常。


以上是关于getComputedStyle的主要内容,如果未能解决你的问题,请参考以下文章

getComputedStyle 属性值

JS使用getComputedStyle()方法获取CSS属性值

JS使用getComputedStyle()方法获取CSS属性值

return,this,arguments,currentStyle和getComputedStyle小析

getComputedStyle

getComputedStyle方法的那些事