弹性运动
弹性运动 速度 = 初始速度 +/- 加速/减速速度 - 摩擦力
加速/减速速度 的速度会时时改变,
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.move{
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 0;
}
.tagget{
width: 1px;
height: 100px;
background: black;
position: absolute;
left: 300px;
}
</style>
</head>
<body>
<div class="move"></div>
<div class="tagget"></div>
<script>
// 弹性运动 速度 = 初始速度 +/- 加速/减速速度 - 摩擦力
var divMove = document.getElementsByClassName('move')[0];
var divTagger = document.getElementsByClassName('tagget')[0];
var timer = null;
function move (dom , target){
clearInterval(timer);
var iSpeed = 0; // 初速度
var accelerate = 3; // 加减速的速度
var friction = 0.8; // 摩擦力
timer = setInterval(() => {
accelerate = (target - dom.offsetLeft) / 4;
iSpeed += accelerate;
iSpeed *= friction;
if( Math.abs(iSpeed) < 1 && Math.abs(target - dom.offsetLeft) < 1){
clearInterval(timer);
dom.style.left = target +'px';
}else{
dom.style.left = dom.offsetLeft + iSpeed + 'px'
}
}, 30)
}
divMove.onclick = function(){
move(this,300)
}
</script>
小demo
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
margin: 300px auto;
width: 800px;
height: 98px;
border: 1px solid black;
line-height: 98px;
text-align: center;
padding: 0px;
list-style: none;
position: relative;
}
li{
width: 200px;
height: 100px;
float: left;
}
.by{
position: absolute;
background: rgba(0, 0, 0, 0.4);
z-index: -1;
}
</style>
</head>
<body>
<ul class="container">
<li class="list" style="background: red; opacity: 0.5;"></li>
<li class="list" style="background: blue; opacity: 0.5;"></li>
<li class="list" style="background: yellow; opacity: 0.5;"></li>
<li class="list" style="background: green; opacity: 0.5;"></li>
<li class="by"></li>
</ul>
<script>
// 弹性运动 速度 = 初始速度 +/- 加速/减速速度 - 摩擦力
var li = document.getElementsByTagName("li");
var by = li[li.length-1];
for (var i = 0 ; i< li.length-1 ; i++){
li[i].onmouseenter = function(e){
move(by, this.offsetLeft)
}
}
var timer = null;
function move (dom , target){
clearInterval(timer);
var iSpeed = 0; // 初速度
var accelerate = 3; // 加减速的速度
var friction = 0.8; // 摩擦力
timer = setInterval(() => {
accelerate = (target - dom.offsetLeft) / 4;
iSpeed += accelerate;
iSpeed *= friction;
if( Math.abs(iSpeed) < 1 && Math.abs(target - dom.offsetLeft) < 1){
clearInterval(timer);
dom.style.left = target +'px';
}else{
dom.style.left = dom.offsetLeft + iSpeed + 'px'
}
}, 30)
}