美文网首页
js运动7 完美运动框架(2)

js运动7 完美运动框架(2)

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

js运动6 完美运动框架 其实有bug
看以下例子,width先结束就会关闭掉定时器

HTML

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>完美运动框架</title>
    <script src="js/move2.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;
            filter: alpha(opacity:30);
        }
    </style>

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

效果

jsSport7.gif

改move.js

加入了stop标志位

/**
 * Created by admin on 2017/3/20.
 */
/**
 *
 * @param obj 运动的对象
 * @param json {width:400, height:400}
 * @param fn 回调
 */
function move(obj, json, fnEnd){
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
        var stop = true;
        for(var attr in json){
            var target = json[attr];
            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){
                stop = false;
                if(attr == "opacity"){
                    obj.style.opacity = (cur + speed)/100;
                    obj.style.filter = "alpha(opacity:"+(cur+speed)+")";
                }
                else
                    obj.style[attr] = (cur + speed) + "px";
            }
            console.log(obj + "---" + attr+ " stop " +stop );
        }
        if(stop){
            clearInterval(obj.timer);
            console.log(obj + "---" + attr+ " to " +target+ " is over ");
            if(fnEnd)fnEnd();
        }

    }, 30)
}

效果

jsSport8.gif QQ图片20170320143743.png QQ图片20170320143826.png

相关文章

网友评论

      本文标题:js运动7 完美运动框架(2)

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