问答详情
源自:4-3 任意属性值(一)

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

<!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>


提问者:ZXJ03 2016-10-20 22:25

个回答

  • 嘛也不会
    2016-10-20 22:56:34
    已采纳

            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 里面 否则定时器不能每次获得新的属性值