美文网首页
js运动5 链式运动框架

js运动5 链式运动框架

作者: maomizone | 来源:发表于2017-03-20 13:11 被阅读0次

一环扣一环

让同一个对象对待一种事件(例如onmouseover产生多种属性变化,但不是同时的

HTML

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>运动框架</title>
    <script src="js/move.js"></script>
    <style>
        body{
            background-color: #cccccc;
        }
        div{
            width: 100px;
            height: 100px;
            background-color: crimson;
            border: 2px solid white;
            margin: 10px;
            float: left;
            color: white;
            text-align: center;
            line-height: 100px;
            font-size: 15px;
            opacity: 0.3;
        }
    </style>

    <script>
        window.onload = function(){
            var div = document.getElementsByTagName("div")[0];
            div.onmouseover = function(){
                var _this = this;
                move(_this, "width", 200, function(){
                    move(_this, "height", 200, function(){
                        move(_this, "opacity", 100);
                    });
                });
            }
            div.onmouseout = function(){
                var _this = this;
                move(_this, "opacity", 30, function(){
                    move(_this, "height", 100, function(){
                        move(_this, "width", 100);
                    });
                });
            }
        }
    </script>
</head>
<body>
<div></div>
</body>
</html>

move.js 多了一个参数fn

/**
 * Created by admin on 2017/3/20.
 */
/**
 *
 * @param obj 运动的对象
 * @param attr 运动的对象需要改变的属性
 * @param target 目标点 宽度 高度 字号 都是int类型 对于透明度 这是float类型
 * @param fn 回调 
 */
function move(obj, attr, target, fn){
    clearInterval(obj.timer);

    obj.timer = setInterval(function(){
        if(attr == "opacity")
            var cur = parseFloat(getStyle(obj, attr))*100;
        else
            var cur = parseInt(getStyle(obj, attr));

        var speed = (target - cur)/6;
        speed = speed>0 ? Math.ceil(speed) : Math.floor(speed);

        if(cur == target){
            clearInterval(obj.timer);
            console.log(obj + "---" + attr+ " to " +target+ " is over ");
            fn();
        }else{
            if(attr == "opacity")
                obj.style[attr] = (cur + speed)/100;
            else
                obj.style[attr] = (cur + speed) + "px";
        }
    }, 30)
}


/**
 * 获取行间/内联/外部样式,无法设置
 * @param obj
 * @param attr
 */
function getStyle(obj, attr){
    if(obj.currentStyle){
        return obj.currentStyle[attr];
    }else{
        return getComputedStyle(obj, false)[attr];
    }
}

效果

jsSport5.gif

相关文章

网友评论

      本文标题:js运动5 链式运动框架

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