速度版动画

轩陌

分类: 实战案例 3097 2

学前端也那么久了,js放着几个月打酱油,到今天才学到定时器,时间匆匆的走了,我还在原地一样,自己掉队了,进度慢了点,我还在努力,对自己说一声加油!

下边是一个速度版的简单动画,结合前边的知识做个小练习。

代码如下:


*{margin: 0;padding: 0;font-family: "microsoft yahei";}
#inp{position: absolute;top: 0;right: 0;bottom: 0;left: 0;width: 300px;height: 300px;margin: auto;border: 1px solid #03A9F4;}
#inp p{text-align: center;line-height: 30px;}
input{margin: 10px 24px;border: none;outline: none;}
input.attr{width: 245px;height: 30px;padding-left: 5px;border: 1px solid #03A9F4}
input.submit{right: 0;width: 250px;height: 30px;cursor: pointer;}
#box{position: absolute;width: 100px;height: 100px;background: #f476ef;}

 


window.onload = function () {
    var oInp = document.getElementById('inp');
    var aText = oInp.getElementsByClassName('attr');
    var oBtn = oInp.getElementsByClassName('submit')[0];
    var oBox = document.getElementById('box');
    oBtn.onclick = function () {
        oBox.style.cssText = aText[0].value;
        move(oBox, aText[1].value, aText[2].value, Number(aText[3].value));
    }

    function move(obj, attr, target, speed) {
        //获取初始值
        var attrS = parseInt(getStyle(obj, attr));
        //获取结束值
        var attrE = parseInt(target);
        //初始值与结束值比较,决定累加累减
        if (attrS >= attrE) speed = -speed;
        var time = setInterval(function () {
            attrS += speed;
            var attrN;
            attrN = speed < 0 ? attrS <= attrE : attrS >= attrE;
            if (attrN) {
                attrS = attrE;
                clearInterval(time);
            }
            obj.style[attr] = attrS + 'px';
        }, 40);
    }
    //获取样式
    getStyle(oBox, aText[1].value);

    function getStyle(obj, attr) {
        return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
    }
}

<div id="inp">
    速度版动画
    <input class="attr" type="text" value="" placeholder="给出两个定位值 如:top:0;left:0; 单位px" />
    <input class="attr" type="text" value="" placeholder="需要运动的方向 top bottom left right" />
    <input class="attr" type="text" value="" placeholder="运动的目标 number" />
    <input class="attr" type="text" value="" placeholder="运动速度 number" />
    <input class="submit" type="button" value="执行动画" />
</div>
<div id="box"></div>

DEMO展示

  • 4人 Love
  • 0人 Haha
  • 0人 Wow
  • 0人 Sad
  • 0人 Angry
demo

作者简介: 轩陌

打赏

生命的意义在于折腾,一直努力成长中,期待梦想实现的那刻。

共 2 条评论关于 “速度版动画”

Loading...