美文网首页
3原生JS的animate运动(width,height,lef

3原生JS的animate运动(width,height,lef

作者: pingping_log | 来源:发表于2017-09-01 19:17 被阅读0次

同上一篇添加了

  1. 改变box的width,height,left,top值(遍历所有需要修改的值)
  2. 需要去判断fn执行的时机,只有fn的值为函数时,说明用户需要执行新的功能,进行调用;否则什么也不做
    if (typeof fn == "function") {
    fn();
    }
  3. 每个元素都有一个关联的style对象,可以用来确定和修改行内的样式。
    IE不支持getComputedStyle()方法,但为所有元素都提供了能够返回相同信息currentStyle属性。
  4. 使用flag假设成立法,保证所有的样式均到达指定位置,再设置清除
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<style type="text/css">
* {
    margin: 0;
    padding: 0;
}
#box {
    width: 100px;
    height: 100px;
    background-color: pink;
    position: absolute;
}
</style>
<body>
<button id="btn">按钮</button>
<div id="box"></div>
<script type="text/javascript">
    var btn = document.getElementById('btn'); 
    var box = document.getElementById('box');
    var timer = null;
    btn.onclick = function () {
        animate(box, {
            width: 500,
            height: 500,
            top: 200,
            left: 300
        }, function() {
            animate(box, {
                width: 100,
                height: 100,
                top: 80,
                left: 120
            });
        });
    } 
    function animate(tag, obj, fn) {
        clearInterval(tag.timer);
        tag.timer = setInterval(function () {
            var flag = true;
            for(var k in obj) {
                var styleName = k;
                var target = obj[k];

                var current = parseInt(getStyle(tag, styleName)) || 0;
                var step = (target - current) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                current = current + step;
                tag.style[styleName] = current + 'px';
                if(current != target) {
                    flag = false;
                }
            }
            if(flag) {
                clearInterval(tag.timer);
                fn && fn();
            }
        },30)
    }

    function getStyle(tag, styleName) {
        if(tag.currentStyle) {
            return tag.currentStyle[styleName];
        } else {
            return getComputedStyle(tag, null)[styleName];
        }
    }
</script>
</body>
</html>

相关文章

网友评论

      本文标题:3原生JS的animate运动(width,height,lef

      本文链接:https://www.haomeiwen.com/subject/llarkxtx.html