2015.7.22js-17(任意值的运动框架)

1.原理:任意变高变宽变透明度的运动,有三个参数,obj,attr,iTarget,对象,样式属性,目标,通过currentStyle和getComputedStyle获取样式属性值,然后将其改变。

案例:多张图片的透明度变化:

js

function startMove(obj,attr,iTarget){        //有三个参数,对象,样式属性名,目标值
        clearInterval(obj.timer);                //每次执行前先清除定时器
        obj.timer = setInterval(function(){        //obj.timer每个对象的定时期
            var cur = 0;                        //先定义获取的样式名
            if(attr == "opacity"){                //因为opacity的透明度的运动计算方法与其他运动不一样,所以单独拿出来
                cur = parseFloat(getStyle(obj,attr))*100;            //获取的是opacity是小数0.3 ,但目标值是整数,先转换成30,所以要乖100
            }else{
                cur = parseInt(getStyle(obj,attr));        //其他样式,如height,width,border,font-size
            }
            var speed = (iTarget - cur)/6;                //定义缓冲的运动速度
            speed = speed > 0?Math.ceil(speed):Math.floor(speed);    //但凡是缓冲运动都要取整
            if(cur == iTarget){                            
                clearInterval(obj.timer);                //判断是否到达目标值,然后停止定时期
            }else{
                if(attr == "opacity"){                    //opacity透明度的运动方法
                    obj.style.filter = "alpha(opacity:"+(cur+speed)+")";
                    obj.style.opacity = (cur+speed)/100;
                }else{
                    obj.style[attr] = cur + speed + "px";
                }
            }
        },Math.round(1000/60));
    }

  var oDiv = document.getElementById("wrap");
  var aImg = oDiv.getElementsByTagName("img");
  var timer = null;

  for(var i = 0, len = aImg.length; i < len; i++){
    aImg[i].onmouseover = function(){
      startMove(this,"width",300);
    }
    aImg[i].onmouseout = function(){
      startMove(this,"width",100);
    }
  }

  function getStyle(obj,name){ //有两个参数,对象和样式属性名
    if(obj.currentStyle){
      return obj.currentStyle[name]; //IE
    }else{
      return getComputedStyle(obj,false)[name]; //chrome,firefox
    }
  }

HTML

<style type="text/css">
img{width:200px;height:100px;filter:alpha(opacity:30); opacity:0.3;cursor:pointer;margin:0;padding:0;background:red;}
</style>
<div id="wrap">
    <img src="images/slide_01.jpg" />
    <img src="images/slide_02.jpg" />
    <img src="images/slide_03.jpg" />
</div>
posted @ 2015-07-22 15:07  AlanTao  阅读(210)  评论(0)    收藏  举报