There is a Bug in offset

盒子模型引起的疑问

style下的width是内容的宽度,那么你知不知道offsetWidth获取的是盒子整个的宽度,包括2*(padding + margin + border) + width,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
#div1{
width:200px;
height: 200px;
background-color:#DBDBDB;
border:2px solid #000;
}
</style>

</head>
<body>
<div id="div1"></div>
<script type="text/javascript">
var oDiv=document.getElementById("div1");
console.log(oDiv.offsetWidth);//204
console.log(oDiv.style.width);//空白...
window.onload=function(){
startMove();
};
function startMove(){
setInterval(function(){
oDiv.style.width=oDiv.offsetWidth-1+"px";//201 202...
},30);
}
console.log(getComputedStyle(oDiv,":after").content);
console.log(getComputedStyle(oDiv,":hover").width);
</script>

</body>
</html>

原来offset引起的

以为是缩小的结果,结果是增大,这是怎么回事呢,观察上面的输出得出offset造成的结果
offset获取的是大盒子的值,style设置的是内容的width,结果就是在增大

学会用getComputedStyle,IE支持currentStyle独有

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
#div1{
width:200px;
height: 200px;
background-color:#DBDBDB;
border:2px solid #000;
}
</style>

</head>
<body>
<div id="div1"></div>
<script type="text/javascript">
var oDiv=document.getElementById("div1");
window.onload=function(){
startMove();
};
function startMove(){
setInterval(function(){
oDiv.style.width=parseInt(getStyle(oDiv,"width"))-1+"px";
},30);
}
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[atr];
}else{
return getComputedStyle(obj,null)[atr];
}
}
console.log(getComputedStyle(oDiv,":after").content);
console.log(getComputedStyle(oDiv,":hover").width);
</script>

</body>
</html>

不过还是存在一个问题getComputedStyle(element,伪类).attr当为hover时获取不到hover的属性,待解决……