我需要实现的功能是
1.当鼠标移入div1时,宽和高匀速变化到目标点200.
2.当鼠标移出div1时,高和高匀速变化到目标点100.
3.调用函数时speed传参只传正数,在move运动函数内部进行speed的正负判断。
故障:下面的代码目前的效果是鼠标移入时正常,移出时没有匀速变化的效果。
为了检测故障,我加了一条测试用的代码alert(startValue+':'+json[attr]+':'+speed);,测出的结果是,当div1从200运动到100时,弹出的2次结果中的speed第一次是负的,第二次居然是正的。虽然知道这是导致bug的原因,但我不知道为什么会在鼠标移出时,速度会弹出负的。
//下面是完整代码。请哪位高手帮忙看一下,感激不尽。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
#div1{width: 100px;height: 100px;background-color: red;}
</style>
</head>
<body>
<div id="div1"></div>
</body>
<script>
var div1=document.getElementById('div1');
var timer=null;
div1.onmouseover=function(){
move({width:200,height:200},10);
}
div1.onmouseout=function(){
move({width:100,height:100},10);
}
/*--------------------运动框架-------------------------*/
function move(json,speed){
clearInterval(timer);
startValue=0;
for(var attr in json){
startValue=parseInt(getStyle(div1,attr));
speed=startValue>json[attr]?-speed:speed;//判断速度正负。
alert(startValue+':'+json[attr]+':'+speed);//测试用。
}
timer=setInterval(function(){
for(var attr in json){
changeValue=0;
changeValue=parseInt(getStyle(div1,attr));
if((speed<0&&changeValue+speed<=json[attr])||(speed>0&&changeValue+speed>=json[attr])){
div1.style[attr]=json[attr]+'px';
clearInterval(timer);
}
else{
div1.style[attr]=changeValue+speed+'px';
}
}
},30);
}
/*--------------------获取样式的函数-------------------------*/
function getStyle(obj,attr)
{
return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj,null )[attr];
}
</script>
</html>
相似问题