tx4-封装运动框架基本函数(多个属性)

还没加定时器的


<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #box{
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
            left: 10px;
            top: 50px;
        }
    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:200,left:200});
    }
    btn400.onclick = function () {
        animate(box,{top:200});
    }
    function animate(obj,json){ //参数1:对象 参数2:json
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            //开始遍历json
            for(var attr in json){
                //当前位置
                var current = parseInt(getStyle(obj,attr));//得到当前的样式,结果是带单位的,要用parseInt
                //计算步长
                var step = (json[attr] - current)/10;
                step = step>0 ? Math.ceil(step) : Math.floor(step);
                obj.style[attr] = current + step + "px";
            }

        },30);
    }
    function getStyle(obj,attr){
        if(obj.currentStyle){ //ie
            return obj.currentStyle[attr];
        }else{
            return window.getComputedStyle(obj,null)[attr]; // w3c
        }
    }
script>

你可能感兴趣的:(tx4-封装运动框架基本函数(多个属性))