JavaScript中的运动大多靠定时器来实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #div1 { width: 100px; height: 100px; background: blue; position: absolute; top: 50px; left: 0; right: 1436px; } </style> <script> var timer = null; function startMove() { var oDiv = document.getElementById('div1'); clearInterval(timer); timer = setInterval(function () { if (oDiv.offsetLeft >= document.documentElement.clientWidth-oDiv.offsetWidth) { clearInterval(timer); oDiv.style.left = document.documentElement.clientWidth-oDiv.offsetWidth } else { oDiv.style.left = oDiv.offsetLeft + 10 + 'px'; } console.log(document.documentElement.clientWidth-oDiv.offsetWidth); }, 30); } </script> </head> <body> <input id="btn" type="button" value="开始运动" οnclick="startMove()"> <div id="div1"></div> </body> </html>
以上代码设置一个30ms执行一次的定时器来给div的style的left属性不断加10来实现右移。
oDiv.offsetleft为oDiv当前left的值。
document.documentElement.clientWidth-oDiv.offsetWidth 浏览器宽度-div的宽度 保证div运动到窗口右端然后停止。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #div1 { width: 150px; height: 200px; background-color: yellow; position: absolute; left: -150px; } #div1 span { position: absolute; width: 18px; height: 65px; background: blue; line-height: 32px; right: -18px; top: 40px; } </style> <script> window.onload = function () { let oDiv = document.getElementById('div1'); oDiv.onmouseover = function () { startMove(0) }; oDiv.onmouseout = function () { startMove(-150) } }; let timer = null; function startMove(po) { let oDiv = document.getElementById('div1'); let speed = 5; if (oDiv.offsetLeft > po) { speed = -5 } clearInterval(timer); timer = setInterval(function () { if (oDiv.offsetLeft === po) { clearInterval(timer); } else { oDiv.style.left = oDiv.offsetLeft + speed + 'px' } }, 30) } </script> </head> <body> <div id="div1" οnmοuseοver="startMove(0)"> <span>出来</span> </div> </body> </html>
以上代码实现一个侧栏。当鼠标移动到蓝色div时,触发一个mouseover事件,使黄色的隐藏侧栏滑出。