1简单运动(匀速)
盒{ 宽度:100 px; 身高:100 px; background - color: # ccc; 位置:绝对的; 前:200像素; 左:0; } & lt;脚本type=" text/javascript祝辞 var obtn=document.querySelector(“按钮”); var obox=document.querySelector (“.box”);//设置速度 var速度=10; obtn.onclick=function () {//1先清除掉定时器 clearInterval (obox.timer); obox。计时器=setInterval(函数(){ obox.style。左=obox。offsetLeft +速度+“px” },30); } & lt;/script>
2指定运动的距离(匀速)
js代码:
& lt;脚本type=" text/javascript祝辞 var obtn=document.querySelector(“按钮”); var obox=document.querySelector (“.box”); var mysound。=500;//设置速度 var速度=10; obtn。onclick=function () {//1先清除掉定时器 clearInterval (obox.timer); obox。计时器=setInterval(函数(){ obox.style。左=obox。offsetLeft +速度+“px” 如果(getStyle (obox '左')祝辞=mysound。) {//已经到达目的地了 obox.style。左=mysound。+“px”;//同时我们还需要清除掉定时器 clearInterval (obox.timer); } }, 30); }//封装获取样式的方法不带px单位的 函数getStyle(避署、风格){ 让结果=避署。currentStyle吗?避署。currentStyle(风格):getComputedStyle(避署,null)(风格); 回归方法(结果); } & lt;/script>
3缓冲运动(速度由快到慢,直至停止)
缓冲运动的原理:速度由距离决定。即:距离越大速度越大,距离越近,速度越小,直至为0。
4加速运动(速度由慢到快,直至到达终点)
加速运动和缓冲运动相反,代码也不需要做过多的修改
原理:根据移动的距离来设置速度,也就是正比关系
var obtn=document.querySelector(“按钮”); var obox=document.querySelector (“.box”); var mysound。=500;//设置速度 var速度=零; obtn。onclick=function () {//1先清除掉定时器 clearInterval (obox.timer); obox。计时器=setInterval(函数(){//1获取当前运动的距离 var curPosition=getStyle (obox '左');//2速度是变化的动态计算 速度=(curPosition/10) | | 1;//对速度进行取整操作//装天花板:向上取整//地板:向下取整//3 *需要对速度进行取整否则达不到临界值 速度=速度比;0 ?Math.ceil(速度):Math.floor(速度); obox.style。左=obox。offsetLeft +速度+“px”; console.log(速度); 如果(getStyle (obox '左')祝辞=mysound。) { console.log(“我执行了没'); obox.style。左=mysound。+“px”; clearInterval (obox.timer); } }, 30); }//封装获取样式的方法不带px单位的 函数getStyle(避署、风格){ 让结果=避署。currentStyle吗?避署。currentStyle(风格):getComputedStyle(避署,null)(风格); 回归方法(结果); }