任务描述:
当鼠标移入“变宽”矩形时,该矩形宽度逐渐增加至400px,移出该矩形,宽度逐渐恢复至初始值;当鼠标移入“变高”矩形时,该矩形高度逐渐增加至400px,移出该矩形,高度逐渐恢复至初始值。
效果图:
<!DOCTYPE html>
<html><head lang="zh-CN">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>多个div淡入淡出</title>
<style>
div {
width: 200px;
height: 200px;
margin: 20px;
float: left;
background: yellow;
}
</style>
</head>
<body>
<div id='div1'>变宽</div>
<div id='div2'>变高</div> <script type="text/javascript">
//补充代码
</script>
</body></html>
参考代码:
function getStyle(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; }
else { return getComputedStyle(obj, null)[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)}
oDiv1 = document.getElementById('div1');
oDiv2 = document.getElementById('div2');oDiv1.onmouseover = function () {
startMove(this, 'width', 400)
}oDiv1.onmouseout = function () {
startMove(this, 'width', 200)
}oDiv2.onmouseover = function () {
startMove(this, 'height', 400)
}oDiv2.onmouseout = function () {
startMove(this, 'height', 200)
}