100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > JavaScript获取样式值的几种方法学习总结

JavaScript获取样式值的几种方法学习总结

时间:2024-04-16 16:38:33

相关推荐

JavaScript获取样式值的几种方法学习总结

本人经过整理总结出以下获取样式值的方法,如有错误请各位大佬指正。有四种方法:style,currentStyle,getComputedStyle,rules 与 cssRules方法。

1. style

用法:document.getElementById(“id”).style.property=”值”。

例子:

<style>.yellow{height:200px;width:200px;background: yellow;}</style></head><body><div id="div1" class="yellow" style="color:red"></div><script>var div1=document.getElementById("div1");div1.onclick=long;function long(){alert(div1.style.width);//空值alert(div1.style.color);//reddiv1.style.color="blue";div1.style.width="300px";alert(div1.style.color);//bluealert(div1.style.width);//300px}</script>

总结:style对象只能读写内联样式的值,不能够读写内部样式和外部样式的值。经过测试兼容IE8,Chrome,Firefox浏览器。

2.currentStyle

用法:document.getElementById(“id”).currentStyle.property。

<style>.yellow{height:200px;width:200px;background: yellow;}</style></head><body><div id="div1" class="yellow"></div><script>var div1=document.getElementById("div1");div1.onclick=long;function long(){//div1.currentStyle.width="300px";//Uncaught TypeError: Cannot set property 'width' of undefinedalert(div1.currentStyle.width);//200px}</script>

总结:currenStyle只能读取元素最终用到的样式值,不能用来设置相关值。经过测试只对IE8浏览器兼容,Chrome和Firefox,Safari不兼容。

3.getComputedStyle

用法:window.getComputedStyle(元素).property

<style>.yellow{height:200px;width:200px;background: yellow;}</style></head><body><div id="div1" class="yellow"></div><script>var div1=document.getElementById("div1");div1.onclick=long;function long(){//window.getComputedStyle(div1).width="300px";// Failed to set the 'width' property on 'CSSStyleDeclaration'alert(window.getComputedStyle(div1).width);//200px}</script>

总结:getComputedStyle只能读取元素最终用到的样式值,不能用来设置相关值。经过测试对Chrome和Firefox,Safari兼容,对IE8浏览器不兼容。

4.rules 与 cssRules方法

用法:document.styleSheets[0].rules[0];

document.styleSheets[0].cssRules[0];

<style>.yellow{height:200px;width:200px;background: yellow;}#div1{height:300px;}</style></head><body><div id="div1" class="yellow"></div><script>var div1=document.getElementById("div1");div1.onclick=long;function long(){if(document.styleSheets[0].rules){//兼容IE8,Chrome,不兼容Firefoxvar s1=document.styleSheets[0].rules[0];var s2=document.styleSheets[0].rules[1];alert(s1.style.background);//yellow alert(s2.style.background);//空值 s1.style.background="red";//.yellow中背景色设为红色 s2.style.background="blue";//#div1中背景色设为蓝色,最终根据css就近规则显示蓝色 alert(s1.style.background);//red alert(s2.style.background);//blue }else{//兼容Firefox,Chrome,不兼容IE8var s1=document.styleSheets[0].cssRules[0];var s2=document.styleSheets[0].cssRules[1];alert(s1.style.height);//200px alert(s2.style.height);//300px s1.style.height="400px";s2.style.height="600px";alert(s1.style.height);//400px alert(s2.style.height);//600px }}</script>

总结:rules和cssRules可以读写内部样式,外部样式的样式值。经过测试Chrome两者都兼容,Firefox兼容cssRules对rules不兼容,IE8浏览器兼容rules对cssRules不兼容。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。