js 多物体运动框架

多物体运动框架
注意:在多物体运动中什么东西都不能公用

多个物体同时运动
例子:多个Div,鼠标移入biankuan
单定时器,存在问题
每个Div一个定时器
总结:
参数问题:
当运动当前的div的时候可以传参数
onStart(obj,tag);
obj为当前运动的div 调用时用this
tag表示运动的终点距离
开一个定时器(当三个div一起运动时会卡)
所以利用for循环开三个定时器
步骤:
1.设置定时器 var timer=null;
2.关闭定时器
clearInterval(obj.timer);
3.开启定时器:
obj.timer=setInterval(function(){},30);
4.缓冲时设置速度 并且要取整
5.判断当前位置与目标位置是否相等

 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
div{width:200px;
height:50px;
background:#F00;
margin:10px;
}
</style>
<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(){
             onStart(this,400);
            };
            aDiv[i].onmouseout=function(){
             onStart(this,100);
            };
            
        }
    }
    //var timer=null;
function onStart(obj,tag){
    clearInterval(obj.timer);
    obj.timer=setInterval(function(){
        var speed=(tag-obj.offsetWidth)/6;
        speed=speed>0?Math.ceil(speed):Math.floor(speed);
        if(obj.offsetWidth==tag){
            clearInterval(obj.timer);
            }else{
                obj.style.width=obj.offsetWidth+speed+'px';
                }
        
        },30);
    
    }
</script>
</head>



<body>

<div></div>
<div></div>
<div></div>
</body>
</html>

多物体运动框架
定时器作为物体的属性
参数的传递:物体、目标值
例子:多个Div淡入淡出
所有东西都不能公用
属性与运动对象绑定:速度、其他属性值(透明度等) 

 

 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
div{
    width:200px;
    height:200px;
    background:red;
    filter:alpha(opacity:30);
    opacity:0.3;
    margin:10px;
    float:left;
    
}

</style>
<script>
window.onload=function(){
    var aDiv=document.getElementsByTagName('div')
    for(var i=0;i<aDiv.length;i++){
        aDiv[i].timer=null;
        aDiv[i].alpha=30;
        aDiv[i].onmouseover=function(){
             onStart(this,100);
            };
            aDiv[i].onmouseout=function(){
             onStart(this,30);
            };
            
        }
    }
//var alpha=30;
function onStart(obj,tag){
    clearInterval(obj.timer);
    obj.timer=setInterval(function(){
        var speed=(tag-obj.alpha)/6;
        speed=speed>0?Math.ceil(speed):Math.floor(speed);
        if(tag==obj.alpha){
        clearInterval(obj.timer);
            }else{
                obj.alpha+=speed;
                obj.style.filter='alpha(opacity:'+obj.alpha+')';
                obj.style.opacity=obj.alpha/100;
                
                
                }
        },30);
    
    
    }
</script>
</head>

<body>
<div></div>
<div></div>
<div></div>
</body>
</html>

 

posted @ 2017-05-14 14:07  943987243  阅读(610)  评论(0编辑  收藏  举报