offset--BUG

offsetWidth所获取的宽度并不是div的实际宽度,它包括div的width、border等。

在JS函数中,可以通过obj.style.width来获取div的实际宽度,但是这种方式style只能获取行间样式,所以需要一个函数调用css中样式,代码如下:

 function getStyle(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
}
else {
return getComputedStyle(obj, false)[name];
}
}

setInterval(function () {
var oDiv = document.getElementById('div1');

oDiv.style.width = parseInt(getStyle(oDiv, 'width')) - 1 + 'px';
},
30);

现在我们来用一个案例来掩饰去掉offset如何实现

代码:
 
 
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
div {
width: 200px;
height: 200px;
margin: 20px;
float: left;
background: yellow;
border: 10px solid black;
font-size: 14px;
}
</style>
<script>
window.onload = function () {
var oDiv1 = document.getElementById('div1');

oDiv1.onmouseover = function () {
startMove(this, 'height', 400);
};
oDiv1.onmouseout = function () {
startMove(this, 'height', 200);
};

var oDiv2 = document.getElementById('div2');

oDiv2.onmouseover = function () {
startMove(this, 'width', 400);
};
oDiv2.onmouseout = function () {
startMove(this, 'width', 200);
};

var oDiv3 = document.getElementById('div3');

oDiv3.onmouseover = function () {
startMove(this, 'fontSize', 50);
};
oDiv3.onmouseout = function () {
startMove(this, 'fontSize', 14);
};

var oDiv4 = document.getElementById('div4');

oDiv4.onmouseover = function () {
startMove(this, 'borderWidth', 100);
};
oDiv4.onmouseout = function () {
startMove(this, 'borderWidth', 10);
};
};

function getStyle(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
}
else {
return getComputedStyle(obj, false)[name];
}
}

function startMove(obj, attr, iTarget) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var cur = parseInt(getStyle(obj, attr));

var speed = (iTarget - cur) / 6;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

if (cur == iTarget) {
clearInterval(obj.timer);
}
else {
obj.style[attr] = cur + speed + 'px';
}
}, 30);
}
</script>
</head>

<body>
<div id="div1">变高</div>
<div id="div2">变宽</div>
<div id="div3">字体变大</div>
<div id="div4">边框变粗</div>
</body>
</html>
 

运行结果:
 



你可能感兴趣的:(offset--BUG)