代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
.outer{
width: 300px;
height: 300px;
border: 1px solid #000;
margin-left: 100px;
}
.outer .inner{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left: 0;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
<script type="text/javascript">
var i = document.querySelector(".inner");
i.style.backgroundColor = "red";
console.log(i.style.left);
</script>
</body>
</html>
left值可以获取到,可以写,但是输出不了left的值,显示的是空白的,这是怎么回事呢?
你的意思是没设置就获取不了吧,因为style.left只能获取行间的样式(html 里写style),你写在css里是获取不了的,要获取用getComputedStyle,ie的话用currentStyle
//i.style.left = "200px";
console.log(i.style.left); // 获取不了
console.log(getElementStyle(i,"left"));
function getElementStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr]; //第二个参数是伪类
}
}