运动框架中的缓冲运动,缓冲运动是由快到慢
上期讲了匀速运动其实缓冲运动跟匀速运动没什么区别就是多了一个
speed = (target - Rundiv.offsetLeft) / 7
- css样式
div{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0px;
}
span{
width: 1px;
height: 150px;
left: 500px;
position: absolute;
background-color: black;
}
button{
width: 100px;
height: 100px;
margin-top: 150px;
}
- html样式
<div id="qwe"></div>
<span></span>
<button id="abc">运动</button>
- js代码
— 先写代码再讲逻辑
<script>
var Rundiv = document.getElementById("qwe");
var btn = document.getElementById("abc");
var Runtimer = null;
btn.onclick = function(){
fn(Rundiv,500)
}
function fn(dom,target){
clearInterval(Runtimer)
var speed = null;
Runtimer = setInterval(function(){
speed = (target - Rundiv.offsetLeft) /7;
speed = speed > 0 ?Math.ceil(speed) : Math.floor(speed);
if(Rundiv.offsetLeft == target){
clearInterval(Runtimer)
}else{
Rundiv.style.left = Rundiv.offsetLeft + speed +"px";
}
console.log(Rundiv.offsetLeft);
},30)
}
</script>
- 可以看出元素运动是由快到慢的 移动的px也是由多到少直到停止
speed = (target - Rundiv.offsetLeft) /7;
speed = speed > 0 ?Math.ceil(speed) : Math.floor(speed);
if(Rundiv.offsetLeft == target){
clearInterval(Runtimer)
}else{
Rundiv.style.left = Rundiv.offsetLeft + speed +"px";
}
console.log(Rundiv.offsetLeft);
- 先把speed 赋值为 传入500减去div实时的left值然后除以7
- 再把speed赋值一次为 实时left值除以7大于0
Math.ceil(speed) : Math.floor(speed)
- 如果speed值大于0 则为实时值除以7有小数对小数进行下舍,就是只要后面有小数都不要
- 如果speed值小于0 则为实时值除以7 是0.几的时候进行上舍 ,就是如果除以7等于0.1进行上舍就是1
- 判断
if(Rundiv.offsetLeft == target){
clearInterval(Runtimer)
}else{
Rundiv.style.left = Rundiv.offsetLeft + speed +"px";
}
- 判断div实时值是否等于上面传入的500,等于500则走进正确里面清楚计时器
- 判断不等于则走进错误里面进行元素移动到最后越除以7次数多了之后再除以就会有0.几的小数,后面就只会进行1px移动直到实时left值等于500就清除计时器
- 到494px这里开始1px移动