您的位置:首页 > Web前端 > JavaScript

介绍几种运动——匀速、加速、缓冲、弹性

2017-05-27 13:23 288 查看
之前有介绍过弹幕的写法,原理就是利用left值的变化,产生运动。

今天我们再来写几种运动:匀速、加速、缓冲、弹性。

效果图:



html就很简单了,我们还是花时间来看一下js的代码。

<div id='first' class='div-model first'>匀速</div>
<div id='second' class='div-model second'>缓冲</div>
<div id='third' class='div-model third'>加速</div>
<div class='div-model four' id="four">弹性</div>
<button id='btn' class="btn">开始进行运动</button>


匀速运动是最简单的一个,当left的值小于500的时候,加一个定时器,每20毫秒left值加10px;

//匀速运动
var lastPx = 500;
var first = $('first');
var timer = setInterval(function() {
var firstLeft = parseInt(first.style.left);
firstLeft = isNaN(firstLeft) ? 0 : firstLeft;
if (firstLeft >= lastPx) {
clearInterval(timer);
return;
}
first.style.left = firstLeft + 10 + 'px';
}, 20)


缓冲运动,即先加速,后减速直至到达目的地。原理是取到left值,500减去left值再除以8,得到一个speed,如果left+speed小于500就加一个定时器,每50毫秒让left等于这个数值。

var lastPx = 500;
//缓冲运动
var second = $('second');
var speed1 = 0;
var timer2 = setInterval(function() {
var secondLeft = parseInt(second.style.left);
secondLeft = isNaN(secondLeft) ? 0 : secondLeft;
var speed = (lastPx - secondLeft) / 8;
speed = Math.ceil(speed);   // 向上取整

if (secondLeft + speed >= lastPx) {
clearInterval(timer2);
second.style.left = '500px'
return;
}
second.style.left = secondLeft + speed + 'px';

}, 50)


ceil是向上取整的意思。

有了上面的例子,加速运动就很简单了。没50毫秒,使left的值+1;

var lastPx = 500;
//加速运动
var third = $('third');
var speed = 1;
var timer3 = setInterval(function() {
var thirdLeft = parseInt(third.style.left);
thirdLeft = isNaN(thirdLeft) ? 0 : thirdLeft;
if (thirdLeft + speed >= 500) {
clearInterval(timer3);
third.style.left = '500px'
return;
}
third.style.left = thirdLeft + speed + 'px';
speed += 1;
}, 50)


弹性运动就是到达目的地后,抖三抖啊抖三抖。首先要判断是否到达目的地,若left值大于500,则让speed值为负,left+负的speed值,就往回运动,此时就没到达目的地,让speed的值为正,继续往前运动。形成弹性的效果。

var lastPx = 500;
//弹性运动
var four = $('four');
var count = 20;
var speed4 = 19;
var timer4 = setInterval(function() {
var fourLeft = parseInt(four.style.left);
fourLeft = isNaN(fourLeft) ? 0 : fourLeft;
four.style.left = fourLeft + speed4 + 'px';
if (count == 0) {
four.style.left = lastPx + 'px';
clearInterval(timer4);
}
if (fourLeft > lastPx) {
speed4 = 0 - speed4;
count--;
}
}, 20)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript