1、簡單實現分享到html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } #div1 { width: 100px; height: 200px; background: #ccc; position: absolute; left: -100px; top: 30%; } #div1 span { width: 20px; height: 60px; line-height: 20px; text-align: center; left: 100px; top: 70px; background: yellow; position: absolute; /*display: block;*/ } </style> <script> var timer = null; // var iSpeed = null; window.onload = function() { var oDiv = document.getElementById('div1'); oDiv.onmouseover = function() { startMove(0); } oDiv.onmouseout = function() { startMove(-100); } } function startMove(iTarget) { var oDiv = document.getElementById('div1'); var iSpeed = 10; if (oDiv.offsetLeft > iTarget) { //設置速度正負 iSpeed = -iSpeed; } clearInterval(timer); timer = setInterval(function() { if (oDiv.offsetLeft == iTarget) { clearInterval(timer); } else { oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px'; } }, 30) } </script> </head> <body> <div id="div1"> <span>分享到</span> </div> </body> </html>
2、勻速運動框架框架
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } #div1 { width: 100px; height: 100px; background: red; position: absolute; left: 500px; } #div2 { width: 1px; height: 300px; background: black; position: absolute; left: 300px; } </style> <script> window.onload = function() { } var timer = null; function starMove(iTarget) { var oDiv = document.getElementById('div1'); clearInterval(timer); //防止定時器累加 timer = setInterval(function() { var iSpeed = 0; if (oDiv.offsetLeft < iTarget) { iSpeed = 7; } else { iSpeed = -7; } if (Math.abs(oDiv.offsetLeft - iTarget) < 7) { //判斷是否到達終點一次運動的距離都不夠的時候中止 clearInterval(timer); //清除定時器 oDiv.style.left = iTarget + 'px'; } else { oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px'; } }, 30); } </script> </head> <body> <input type="button" name="" value="運動" onclick="starMove(300)"> <div id="div1"></div> <div id="div2"></div> </body> </html>