<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div变宽</title>
<style>
div{
width: 100px;height: 60px; background-color: green;
margin-top: 20px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<script>
window.onload=function(){
var aDiv=document.getElementsByTagName('div');
var i=0;
for(i=0;i<aDiv.length;i++){
aDiv[i].timer=null; //每个div有一个定时器,避免同时用一个div冲突
aDiv[i].onmouseover=function(){
fadeon(this,200);
}
aDiv[i].onmouseout=function(){
fadeon(this,100);
}
}
}
function fadeon(obj,itarget){
clearInterval(obj.timer); //obj对应调用函数中的this
obj.timer=setInterval(function(){
var oSpeed=(itarget-obj.offsetWidth)/8;
oSpeed=oSpeed>0?Math.ceil(oSpeed):Math.floor(oSpeed);
if (obj.offsetWidth==itarget) {
clearInterval(obj.timer);
}else{
obj.style.width=obj.offsetWidth+oSpeed+'px';
}
},30)
document.title=obj.offsetWidth;
}
</script>
</body>
</html>