js怎么获取css属性值

发布时间:2022-05-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了js怎么获取css属性值脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

js获取css属性值的方法:1、通过元素对象的style属性获取,语法“元素对象.style.属性名”;2、通过getComputerStyle属性,语法“getComputerStyle.属性名”。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3脑。

obj.style:

这个方法只能获取写在style属性中的值,而无法获取定义在 <style tyPE=&#39;text/css'>里面的属性

<style type=”text/css”> 
.ss{color:#cdcdcd;}  
</style>  
<div id=”css88″ class=”ss” style=”width:200px; height:200px; background:#333333″>JS获取CSS属性值
</div>  
<script type=”text/javascript”> 
alert(document.getElementById(“css88″).style.width);//200px 
alert(document.getElementById(“css88″).style.color);//空白 
</script>

obj.currentStyle与getComputerStyle

obj.currentStyle只有IE支持,而getComputerStyle在FireFox中支持,这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如“;after”)。如果不需要伪元素信息,第二个参数可以为null。该方法返回一个CSSStyleDeclaration对象,其中包含当前元素的所有计算的样式。

<htML> 
<head> 
<tITle>计算元素样式</title> 
<style> 
#myDiv { 
    width:100px; 
    height:200px; 
} 
</style> 
<body> 
<div id =";myDiv" style=" border:1px solid black"></div> 
 
<script> 
VAR myDiv = document.getElementById("myDiv"); 
var computedStyle = document.defaultView.getComputedStyle(myDiv, null); 
 
alert(computedStyle.backgroundColor); //"red" 
alert(computedStyle.width); //"100px" 
alert(computedStyle.height); //"200px" 
alert(computedStyle.border); //在某些浏览器中是“1px solid black” 
</script> 
</body> 
</head> 
</html>

所以估计兼容浏览器,我们可以封装一个函数来获取一个元素的CSS属性值:

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

【相关推荐:javascript学习教程

以上就是js怎么获取css属性值的详细内容,更多请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的js怎么获取css属性值全部内容,希望文章能够帮你解决js怎么获取css属性值所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: