JavaScript动画1-速度动画

动画实际上就是在一定时间内,改变一个元素的某些属性。

这里简单实现一个JavaScript运动的框架。主要包括:

  1. 速度动画(改变left、right、width、height、opacity)
  2. 缓冲运动
  3. 多物体运动
  4. 任意属性值改变
  5. 链式运动
  6. 多属性同时变化

速度动画

速度动画就是通过改变left、right、width、height、opacity的值来达到动画效果。我们先写一个简单的HTML结构:

<div id="div1">
    <span id="share">分享</span>
</div>

具体CSS样式效果如下图:

JS动画演示1

这里,我用CSS将div的left值设置为-200px,使其移除浏览器窗口:

JS动画演示2

具体CSS参考如下:

body {
    font-family: "SF UI Text", serif, sans-serif;
    font-size: 12px;
}
* {
    margin: 0;
    padding: 0;
}
#div1 {
    width: 200px;
    height: 200px;
    margin-top: 20px;
    background: rgb(43, 221, 255);
    position: relative;
    left: -200px;
    top: 0;
}
#div1 span {
    width: 20px;
    background: rgb(255, 119, 157);
    position: absolute;
    left: 200px;
    top: 75px;
    color: #fff;
    text-align: center;
    cursor: pointer;
    padding: 5px 1px 5px 0;
    border-radius: 0 5px 5px 0;
}
#div1 span:hover {
    background: rgb(255, 84, 137);
}

如果我们想要在鼠标经过span上时,让这个div显示出来,很简单,就是让div的left值变为0。想要动画效果,就需要用到定时器。

window.onload = function () {
    //速度动画
    (function () {
        var div = document.getElementById("div1");
        var timer = null;

        div.onmouseover = function () {
            startMove(0);
        };
        div.onmouseout = function () {
            startMove(-200);
        };
        function startMove(targetPosition) {
            clearInterval(timer);
            var speed = 0;
            if (targetPosition < 0) {
                speed = -10;
            } else {
                speed = 10;
            }
            timer = setInterval(function () {
                if (div.offsetLeft == targetPosition) {
                    clearInterval(timer);
                } else {
                    div.style.left = div.offsetLeft + speed + 'px';
                }
            }, 30);
        }
    })();
};

效果如下:

JS动画演示3

我们把所有代码放在了一个匿名函数(function(){ })()中,并且立即执行,目的是为了防止全局变量的污染。

同理可实现改变透明度的动画:

(function () {
    var div2 = document.getElementById("div2");
    var timer = null;

    div2.onmouseover = function () {
        changeOpacity(60);
    };
    div2.onmouseout = function () {
        changeOpacity(100);
    };

    var opacity = 100;

    function changeOpacity(targetOpacity) {
        clearInterval(timer);
        var speed = 0;
        if (opacity > targetOpacity) {
            speed = -10;
        } else {
            speed = 10;
        }
        timer = setInterval(function () {
            if (opacity == targetOpacity) {
                clearInterval(timer);
            } else {
                opacity = opacity + speed;
                div2.style.opacity = opacity / 100;
            }
        }, 30);
    }

})();

效果如下:

JS动画演示4

HTML结构:

<div id="div2"></div>

CSS:

#div2 {
    width: 200px;
    height: 200px;
    background: rgb(255, 84, 137);
    cursor: pointer;
}

速度动画讲解完了。下一篇讲解运动缓冲效果。

posted @ 2017-04-30 12:34  qiaoer2  阅读(454)  评论(0编辑  收藏  举报