<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> #div1{ width: 100px; height: 100px; background: red; position: absolute; left: 0; } #bg{ width: 1px; height: 500px; background: #000; position: absolute; left: 500px; top: 0; } </style> <script> // 摩擦力:F=fM; window.onload=function(){ var oInput=document.getElementById("input1"); var oDiv=document.getElementById("div1"); var timer=null; var iSpeed=0; oInput.onclick=function(){ startMove(); } function startMove(){ clearInterval(timer); timer=setInterval(function(){ // if(oDiv.offsetLeft<500){ // iSpeed+=(500-oDiv.offsetLeft)/50; // }else{ // iSpeed-=(oDiv.offsetLeft-500)/50; // } iSpeed+=(500-oDiv.offsetLeft)/50; iSpeed*=0.95; if(Math.abs(iSpeed)<=1 && Math.abs(500-oDiv.offsetLeft)<=1){ clearInterval(timer); oDiv.style.left='500px'; iSpeed=0; }else{ oDiv.style.left=oDiv.offsetLeft+iSpeed+"px"; } },30) } } </script> </head> <body> <input type="button" value="开始运动" id="input1" /> <div id="div1"></div> <div id="bg"></div> </body> </html>
弹性:
速度 +=(目标点-当前值)/系数 //系数可以选择:6,7,8都可以
速度*=摩擦系数 //系数可以选择0.7,0.75都可以
缓冲:
var 速度=(目标点-当前值)/系数
速度取整