1、缓冲运动案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>缓冲动画</title>
</head>
<style>
*{margin: 0;padding: 0;}
body,html{width: 100%;height: 100%;}
.main{
width: 100%;height: 100%;position: relative;
}
#box{
width: 240px;height: 100%;background: #333;position: absolute;left: -200px;top: 0;
}
</style>
<body>
<div class="main">
<div id="box"></div>
</div>
</body>
<script>
window.onload = () => {
const boxElem = document.getElementById("box");
let timer = null;
const obj = {
boxElem,
timer
}
cardFunc.apply(obj);
}
//缓冲动画公式 (结束位置 - 开始位置) / 速率
function cardFunc(){
this.boxElem.onmouseover = () => {
velocity(this,0);
}
this.boxElem.onmouseout = () => {
velocity(this,-200);
}
}
function velocity(that,end){
that.timer && clearInterval(that.timer);
that.timer = setInterval(() => {
const speed = end >= 0 ? Math.ceil((end - that.boxElem.offsetLeft) / 10) : Math.floor((end - that.boxElem.offsetLeft) / 10);
//that.boxElem.offsetLeft只能获取到整数位,所以需要向下或者向上取整
if(that.boxElem.offsetLeft === end){
clearInterval(that.timer);
return;
}
that.boxElem.style.left = that.boxElem.offsetLeft + speed + "px";
}, 30);
}
</script>
</html>
2、多物体缓冲运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>多物体运动</title>
</head>
<style>
*{margin: 0;padding: 0;}
.div{width: 200px;height: 100px;margin-bottom: 10px;background: pink;}
</style>
<body>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
</body>
<script>
window.onload = () => {
const divElems = document.getElementsByClassName("div");
for(let i = 0;i < divElems.length;i++){
const item = divElems[i];
item.onmouseover = () => {
velocity(item,600);
}
item.onmouseout = () => {
velocity(item,200);
}
}
}
function velocity(elem,end){//div元素与结束时的长度
elem.timer && clearInterval(elem.timer);
elem.timer = setInterval(() => {
if(end === getAttr(elem,'width')){
clearInterval(elem.timer);
return;
}
const speed = end > getAttr(elem,'width') ? Math.ceil((end - getAttr(elem,'width')) / 10) : Math.floor((end - getAttr(elem,'width')) / 10);
elem.style.width = getAttr(elem,'width') + speed + "px";
},30);
}
function getAttr(obj,attr){
if(obj.currentStyle){//IE下
return parseInt(obj.currentStyle[attr]);
}else{//主流下
return parseInt(getComputedStyle(obj,null)[attr]);
}
}
</script>
</html>