zoukankan      html  css  js  c++  java
  • 多物体运动

    解决了多物体运动定时器之间的干扰,在每个物体上都定义一个定时器,关闭定时器是只关闭自身的定时器,物体就可以独立运动互补干扰了。

    <!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>无标题文档</title>
    <style>
    div{100px; height:50px; background:#F00; margin:10px;}
    
    
    </style>
    <script>
    window.onload=function()
    {
    	var aDiv=document.getElementsByTagName('div');
    	
    	for(var i=0;i<aDiv.length;i++)//为每个div都添加一个事件
    	{
    		aDiv.timer=null;//为每个div添加一个属性,用来存储定时器
    		aDiv[i].onmouseover=function()
    		{
    			onmove(this,400);//那个div调用函数,就传入该div对象,改变该div的属性
    		}
    		aDiv[i].onmouseout=function()
    		{
    			onmove(this,50);
    		}
    	}
    	
    }
    var timer;
    	
    function onmove(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>
    </head>
    
    <body>
    <div id="div1">
    </div>
    <div id="div2">
    </div>
    <div id="div3">
    </div>
    </body>
    </html>
    
  • 相关阅读:
    剑指 Offer 03. 数组中重复的数字
    Leetcode_80: removeDuplicates
    Leetcode_27: removeElement
    Leetcode_26: removeDuplicates
    Leetcode-283: moveZeroes
    Module build failed: Error: Cannot find module 'node-sass’解决
    js实现简单的计算器
    根据经纬度显示地图、地图缩小偏移处理
    js实现滑动到屏幕底部
    【基础】在网页中嵌入页面
  • 原文地址:https://www.cnblogs.com/lzzhuany/p/4536614.html
Copyright © 2011-2022 走看看