4-3問題
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標(biāo)題文檔</title>
<style type="text/css">
*{
margin:0;
padding:0
}
div{
width:200px;
height:100px;
background:#939;
margin-bottom:15px;
border:#000 solid 2px;
filter:alpha(opacity:30);
opacity:0.5;}
</style>
<script type="text/javascript">
window.onload=function(){
var box=document.getElementsByTagName("div");
for(var i=0;i<box.length;i++)
{
? box[i].timer=null;
box[i].onmouseover=function(){
change(this,400);
}
box[i].onmouseout=function(){
change(this,200);}
function change(obj,wid){
clearInterval(obj.timer);
var speed,a=parseInt(getStyle(obj,'width'));
obj.timer=setInterval(function(){
speed=(wid-a)/10; ? ?
speed=speed>0?Math.ceil(speed):Math.floor(speed);
/*if(obj.offsetWidth<wid)
speed=10;
else
speed=-10;*/
if(a==wid)
clearInterval(obj.timer);
else?
obj.style.width=a+speed+'px';
},30)
}
function getStyle(obj,attr){
if(obj.style.currentStyle)
return obj.currentStyle[attr];
else
return getComputedStyle(obj,false)[attr];
}
}
}
</script>
</head>
<body>
<div id="box1"></div>
? ? <div id="box2"></div>
? ? <div id="box3"></div>
</body>
</html>
感覺代碼沒什么錯(cuò)誤,怎么效果是那樣的,好像是定時(shí)器失效了
2016-05-13
變量定義位置錯(cuò)了,應(yīng)該在計(jì)時(shí)器里邊定義
obj.timer=setInterval(function(){
? ?var speed,a=parseInt(getStyle(obj,'width'));
? ?speed=(wid-a)/10;
? ?speed=speed>0?Math.ceil(speed):Math.floor(speed);
? ?if(a==wid)
? ? ? ?clearInterval(obj.timer);
? ?else
? ? ? ?obj.style.width=a+speed+'px';
},30)
建議你規(guī)范一下代碼格式。。。學(xué)會(huì)用瀏覽器調(diào)試。。。