zoukankan      html  css  js  c++  java
  • js多个物体运动的问题1

    问题2

    http://www.cnblogs.com/huaci/p/3854304.html

    用js写一个物体的运动很简单。如果一个页面有多个物体在运动,它会不会出问题呢?

    ok,我们来看一个示例

    让多个div变宽

    现象:onmouseover时,div宽度变宽;onmouseout时,div恢复原大小

    html部分

    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
    <style>
    div { 100px; height:30px; margin:10px; background:green;}
    </style>
    

    js部分

    <script>
    
    window.onload = function(){
    	var aDiv = document.getElementsByTagName("div");
    	
    	for(var i=0; i<aDiv.length; i++){
    		aDiv[i].onmouseover = function(){
    			startMove(this,400);
    		}
    		aDiv[i].onmouseout = function(){
    			startMove(this,100);
    		}
    	}
    }
    
    
    var timer = null;
    function startMove(obj, iTarget){
    	clearInterval(timer);
    	timer = setInterval(function(){
    		var speed = (iTarget - obj.offsetWidth)/6;
    		speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
    		if(obj.offsetWidth == iTarget){
    			clearInterval(timer);			
    		} else {
    			obj.style.width = obj.offsetWidth + speed + "px";			
    		}
    		
    	},30);
    }
    </script>
    

      

    运行后,

    问题:当鼠标在几个div之间来回切换操作时,发现之间的div停住了,收不回去了

    原因:分析上面代码,原来是进入一个新的div操作时,把之前的所有定时器都给关了

    一句话:整个程序就只有一个定时器

    解决:为每个运动对象,都定义一个定时器

    只开启和关闭当前操作的这个运动对象的定时器

    现在给出修改后的完整代码啊

    完整示例:

    <script>
    
    window.onload = function(){
    	var aDiv = document.getElementsByTagName("div");
    	
    	for(var i=0; i<aDiv.length; i++){
    		aDiv[i].timer = null;
          		aDiv[i].onmouseover = function(){
    			startMove(this,400);
    		}
    		aDiv[i].onmouseout = function(){
    			startMove(this,100);
    		}
    	}
    }
    
    
    
    function startMove(obj, iTarget){
    	clearInterval(obj.timer);
    	obj.timer = setInterval(function(){
    		var speed = (iTarget - obj.offsetWidth)/6;
    		speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
    		if(obj.offsetWidth == iTarget){
    			clearInterval(obj.timer);			
    		} else {
    			obj.style.width = obj.offsetWidth + speed + "px";			
    		}
    		
    	},30);
    }
    </script>
    

      

    下一节,问题2

    http://www.cnblogs.com/huaci/p/3854304.html

  • 相关阅读:
    hdu3486 Interviewe (二分+线段树求区间最值)
    hdu2473 JunkMail Filter(并查集)
    hdu3290 The magic apple tree (dfs)
    hdu2610 Sequence one (dfs) &&hdu2611 Sequence two
    hdu1598 find the most comfortable road (枚举+并查集)
    hdu3635 Dragon Balls
    hdu2821 Pusher
    hdu1558 Segment set
    hdu 2514 Another Eight Puzzle
    url传递中文的解决方案
  • 原文地址:https://www.cnblogs.com/huaci/p/3854216.html
Copyright © 2011-2022 走看看