這個效果是體現了元素運動的基本原理。
View Code
<!DOCTYPE HTML><html lang="en-US"><head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .share { position: absolute;top:50px;left:-100px;width:100px;height:300px;background-color: gray;} .share span { position: absolute;right: -24px;top:130px;padding:5px 2px;width:20px;background-color:#dadada;font-size: 12px;color: #fff;text-align: center;cursor: pointer;} </style> <script type="text/javascript"> window.onload = function(){ var share = document.getElementById('s'); var span = share.getElementsByTagName('span')[0]; var speed = 0; var timer = null; share.onmouseover = function(){ startMove(0); } share.onmouseout = function(){ startMove(-100); } function startMove(terminal){ clearInterval(timer); timer = setInterval(function(){ if(share.offsetLeft < terminal){ speed = 10; }else{ speed = -10; } if(share.offsetLeft == terminal){ clearInterval(timer); }else{ share.style.left = share.offsetLeft + speed + 'px'; //console.log(share.offsetLeft) } },30); } } </script></head><body> <div class="share" id="s"> <span>分享到</span> </div></body></html>
寫的時候,遇到3個問題,儘管是看視頻學的。
1、運動的停止條件。
2、觸發的元素。
有必要說這個東西,我之前把span當作了觸發的對象,結果就有許多的bug。熟悉冒泡的話,你就知道事件總是從最底層元素開始的。所以……我沒話說,基礎知識都想半天,還好解決了,不然真的沒有面目了。
3、速度正負判斷。