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


<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">200button>
<button id="btn400">400button>
<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>

你可能感兴趣的:(tx4-封装运动框架多属性函数-定时器-透明度-zIndex)