js计算样式(取得外部样式)

it2022-07-05  113

通过element.style[property]可以设置样式以及取得内联样式,即<div id="myDiv" style="color=#666; width=100px; height=200px;"></div>   通过 document.getElementById("myDiv").style.color可以取得#666; 通过document.getElementById("myDiv").styly.width可以取得100px; 通过document.getElementById("myDiv").style.height可以取得200px;      但是如果外部<link>导入的或者<style></style>标签里写的就不能取得,这样很不完美,今天看过《javascript高级程序设计3》知道document.defaultView对象有一个getComputedStyle属性可以取得外部样式,但是IE下不支持,好在IE有一个currentStyle属性可以取得外部样式,因此可以写一段这样的代码来取得不管是IE还是其他浏览器的外部样式:

function getStyle(obj,attr){if(obj.currentStyle) { return obj.currentStyle[attr]; } else{ return getComputedStyle(obj,false)[attr]; } }

这样就可以通过这个方法取得样式,通过obj.style[attr]=value;来设置样式,这样读取和写入就都有了,就可以方便进行DOM操作。

转载于:https://www.cnblogs.com/ggbd-lie/archive/2012/08/10/2633183.html

相关资源:微信小程序如何引用外部js,外部样式,公共页面模板

最新回复(0)