啊啊啊啊123
2016-09-13 10:48
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>缓冲运动</title> <style type="text/css"> *{margin: 0;padding: 0;} #box{width: 200px;height: 200px;background-color: red;position: relative;left: -200px;top: 0;} #box span{width: 20px;height: 50px;position: absolute;top: 50px;left: 200px;background-color: blue;} </style> <script type="text/javascript"> window.onload=function(){ var obox = document.getElementById('box'); obox.onmouseover = function(){ startmove(0); } obox.onmouseout = function(){ startmove(-200); } } var timer = null; function startmove(iTarget){ //clearInterval(timer); var obox = document.getElementById('box'); // timer = setInterval(function () { // var speed = (iTarget-obox.offsetLeft)/20; // speed = speed > 0?Math.ceil(speed):Math.floor(speed); // if (obox.offsetLeft==iTarget) { // clearInterval(timer); // }else{ // obox.style.left = obox.offsetLeft + speed+'px'; // } // },30) var speed = (iTarget-obox.offsetLeft)/20; speed = speed > 0?Math.ceil(speed):Math.floor(speed); function go() { if (obox.offsetLeft==iTarget) { obox.style.left = obox.offsetLeft + iTarget +'px'; } else{ obox.style.left = obox.offsetLeft + speed+'px'; setTimeout(go, 30); } } go(); } </script> </head> <body> <div id="box"><span>分享</span></div> </body> </html>
要检测就要不断刷新不断去获取某个元素的属性,setTimeout只能执行一次,达不到不断刷新获取属性的作用!
setTimeout(code,time)中的code只会执行一次,如果要code执行多次用setInterval()或settimeout()递归
JS动画效果
113924 学习 · 1443 问题
相似问题