<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#div1,div{
float: left;
width: 100px;
height: 100px;
background: red;
margin-right: 20px;
}
</style>
</head>
<body>
<div id="div1" style="color:black;">111</div>
<script type="text/javascript">
let oDiv=document.getElenmentById('div1');
console.log(oDiv.style.color,'颜色') //black 颜色
console.log(oDiv.style.width,'宽度') // 宽度
</script>
无法获取oDiv.style.width
-
element.style
读取的只是元素的内联样式,即写在元素的 style 属性上的样式;而getComputedStyle
读取的样式是最终样式,包括了内联样式、嵌入样式和外部样式。 -
element.style
既支持读也支持写,我们通过element.style
即可改写元素的样式。而getComputedStyle
仅支持读并不支持写入。我们可以通过使用getComputedStyle
读取样式,通过element.style
修改样式 -
我们可以通过使用
getComputedStyle
读取样式,通过element.style
修改样式。 -
在
ie
浏览器下就是用oDiv1.currentStyle
、在谷歌浏览器获取内部和外部样式getComputedStyle
如果需要调用样式的话
一般需要设置兼容性
function getStyleValue(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr]
}else{
return getComputedStyle(obj,false)[attr]
}
}