PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

js怎么获取css属性值

青灯夜游
青灯夜游 原创
2021-07-07 15:24:30 7911浏览

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

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

obj.style:

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

<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学习教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。