js 任意值变化封装

<!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{width:100px;height:100px;font-size:14px;background:red;border:2px solid #000;margin-top:50px;filter:alpha(opacity:30);opacity:0.3;}
</style>
<script>

window.onload = function(){
    var arrDiv = document.getElementsByTagName('div');
    arrDiv[0].onmouseover = function(){
        startMove(this,'width',300);
    };
    arrDiv[1].onmouseover = function(){
        startMove(this,'height',300);
    };
    
    arrDiv[2].onmouseover = function(){
        startMove(this,'fontSize',100);
    };
    arrDiv[3].onmouseover = function(){
        startMove(this,'borderWidth',50); /*兼容性问题*/
    };
    arrDiv[4].onmouseover = function(){
        startMove(this,'opacity',100); /*兼容性问题*/
    };
    arrDiv[4].onmouseout = function(){
        startMove(this,'opacity',30); /*兼容性问题*/
    };
};

function getStyle(obj,attr){
    return obj.currentStyle ? obj.currentStyle[attr]:getComputedStyle(obj)[attr];
}

function startMove(obj,attr,target){
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
        if(attr == 'opacity'){
            var iCur = parseInt(parseFloat(getStyle(obj,attr))*100); /*避免用到小数,alert(0.07*100) //7.000000001*/
        }else{
            var iCur = parseInt(getStyle(obj,attr));
        }
        var speed = (target-iCur)/8;
        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
        if(iCur == target){
            clearInterval(obj.timer);
        }else{
            if(attr == 'opacity'){
                obj.style[attr] = (iCur+speed)/100;
                obj.style.filter = 'alpha(opacity:'+(iCur+speed)+')';
            }else{
                obj.style[attr] = iCur+speed+'px';
            }
        }
    },30);        
}

</script>
</head>

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

 

posted on 2018-05-02 22:50  朝颜陌  阅读(175)  评论(0编辑  收藏  举报

导航