<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#a{
width: 100px;
height: 100px;
border:1px solid;
}
.color{
background: red;
}
</style>
</head>
<body>
<p id="a">
</p>
</body>
<script type="text/javascript">
var p = document.getElementById('a');
p.className = 'color';
document.write(p.style.backgroundColor);
</script>
输出为空
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
style.backgroundColor
得到是属于这个Element本身的样式,不包括因匹配class而获得的样式。你想要的那个可以用getComputedStyle
。通过
element.style
输出的样式是指输出元素的行内样式。而通过修改className来改变样式这一操作并没有影响到元素的行内样式。楼主需要区分行内样式,内联样式等。也可以这样理解,当前p元素没有设置style属性。
xxx.style.zzz 相当于 xxx.getAttribute('style', 'zzz');
这样你是不是能理解得更好一些?
getComputedStyle 关键在于 computed, 而不是shown
一楼的是正解决 style.backgroundColor得到的是这个标签本身的样式 不含包含css作用以后附加给这个标签的样式 所以用getComputedStyle获取。