为了账号安全,请及时绑定邮箱和手机立即绑定

请问为什么我实现的效果是这样的?

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
	*{
		padding: 0;
		margin: 0;
	}
	.a{
		width: 100px;
		height: 100px;
		background: aquamarine;
		margin-bottom: 10px;
	}

	</style>
	<script type="text/javascript">
		var timer;
		window.onload=function(){
			var div1=document.getElementById("div1");
			var div2=document.getElementById("div2");
			
			div1.onmouseover=function(){
				startMove(this,"height",300);

			}
			div1.onmouseout=function(){
				startMove(this,"height",100);console.log("hello");
			}

			
		}
		function startMove(obj,attr,iTarget){
				
				clearInterval(timer);
				var icur=parseInt(getStyle(obj,attr));
				timer=setInterval(function(){
				speed=(iTarget-icur)/5;
				speed=speed>0?Math.ceil(speed):Math.floor(speed);
				if(icur==iTarget){
					
					clearInterval(timer);
				}
				else{	
						
					obj.style[attr]=icur+speed+'px';console.log("hello");

				}
},50);
			}
		function getStyle(obj,attr){
			
			if(obj.currentStyle){
				return obj.currentStyle[attr];
			}
			else{
				return getComputedStyle(obj,false)[attr];
			}
		}
	</script>
</head>
<body>
	<div id="div1" class="a"></div>
	<div id="div2" class="a"></div>

</body>
</html>


正在回答

1 回答

        var timer;
        window.onload = function(){
            var div1 = document.getElementById("div1");
            var div2 = document.getElementById("div2");
            div1.onmouseover = function(){
                startMove(this,"height",300);
            }
            div1.onmouseout = function(){
                startMove(this,"height",100);
            }
        }
        function startMove(obj,attr,iTarget){
            clearInterval(timer);
            timer = setInterval(function(){
                var icur = parseInt(getStyle(obj,attr));
                var speed = (iTarget - icur) / 5;
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
                if(icur==iTarget){
                    clearInterval(timer);
                }
                else{
                    obj.style[attr] = icur + speed + 'px';
                }
            },50);
        }
        function getStyle(obj,attr){
            if(obj.currentStyle){
                return obj.currentStyle[attr];
            }
            else{
                return getComputedStyle(obj,false)[attr];
            }
        }

 var icur = parseInt(getStyle(obj,attr)); 这句写在setInterval 里面 否则定时器不能每次获得新的属性值

0 回复 有任何疑惑可以回复我~
#1

ZXJ03 提问者

非常感谢!
2016-10-20 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

请问为什么我实现的效果是这样的?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信