tx4-封装运动框架多属性函数-定时器-透明度-zIndex

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #box{
            width: 100px;
            height: 100px;
            position: absolute;
            top: 50px;
            left: 5px;
            background-color: pink;
        }
    </style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="box"></div>
</body>
</html>
<script>
    var btn200 = document.getElementById("btn200");
    var btn400 = document.getElementById("btn400");
    var box = document.getElementById("box");
    btn200.onclick = function () {
        animate(box,{width:200,height:300,top:400,opacity:40,zIndex:3},function(){alert("我是回调函数")});
    }
    btn400.onclick = function () {
        animate(box,{left:100,opacity:10,zIndex:10})
    }
    //多属性运动框架
    function animate(obj,json,fn){
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            var flag = true; //用来判断是否停止定时器 一定要写在遍历外面
            for(var attr in json){
                var current = 0;
                if(attr == "opacity"){
                    current =parseInt(getStyle(obj,attr)*100);
                }else{
                    current =parseInt(getStyle(obj,attr));
                }
                //var current =parseInt(getStyle(obj,attr)); //数值
                var step = (json[attr] - current) /10;
                step = step>0 ? Math.ceil(step) : Math.floor(step);
                if(attr == "opacity"){ //判断用户有没有输入opacity
                    if("opacity" in obj.style){ //判断浏览器是否支持opacity
                        //obj.style.opacity = json[attr];
                        obj.style.opacity = (current+step)/100;
                    }else{
                        obj.style.filter = "alpha(opacity = "+(current+step)+")";
                    }
                }else if(attr == "zIndex"){
                    obj.style.zIndex = json[attr];
                }else{
                    obj.style[attr] = current + step + "px";
                }
                if(current != json[attr]){ //只要目标与json中任意一个值不等 就不能停止定时器 这个一定写在定时器里面
                    flag = false;
                }
            }
            if(flag){
                clearInterval(obj.timer);
                if(fn){fn();}
            }
        },30);
    }
    function getStyle(obj,attr){ //获取属性值
        if(obj.currentStyle){ //i3
            return obj.currentStyle[attr];
        }else{
            return window.getComputedStyle(obj,null)[attr]; //w3c
        }
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值