javascript getComputedStyle() and currentStyle() element.style
今天了解了js里获取样式的几个方法,记录下自己的理解
首先是window.getComputedStyle(dom,null) [attr]
dom----> 是你要获取的元素 eg: div
null —> 我也不知道为什么要有这个 但必须有
如果要获取伪元素(after,before)的样式 null就换成伪元素的字符串形式
eg: window.getComputedStyle(div,“after”)
window.getComputedStyle(dom,null)返回的是一个样式表 是一个对象 里面的值都是最后作用在dom上的 最终看见的样式值 同样没设置的样式 会把系统的默认值返回
在这里给div设置了两个width 但最终因为行内样式的值作用在了div上 所以
window.getComputedStyle()获取的值就是起作用的值
而element.style 获取的是行间样式的值
就没有window.getComputedStyle()方法获取的准确
但window.getComputedStyle(dom,null)[attr]不兼容IE8及以下
所以IE也有一种方式 dom.currentStyle[attr] //注 只有IE支持
eg: div.currentStyle[“width”]
div.currentStyle.width
另外getComputedStyle() and currentStyle() 都是只读 不能改
而 element.style 可以改值
window.getComputedStyle(div,null)[“width”]可这样写 也可
window.getComputedStyle(div,null).width
另外一种兼容函数方法封装代码 getStyle();
function getStyle(ele,prop){
if(window.getComputedStyle){
return window.getComputedStyle(ele,null)[prop];
}else{
return ele.currentStyle[prop];
}
} //prop传入为样式名称的字符串形式width等
//ele为要获取的元素 如 div 等
第一次初认识 如有看到 还能看完 请大家补充不足 thanks
来源:CSDN
作者:qq_45448359
链接:https://blog.csdn.net/qq_45448359/article/details/104198379