js實現滑鼠移入移出元素出來縮排的動畫
阿新 • • 發佈:2019-02-13
<!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>測試</title> <style> body, div, span { margin: 0; padding: 0; } #hide { width: 200px; height: 200px; background-color: aqua; position: relative; left: -200px; } .out { display: inline-block; width: 15px; background-color: blueviolet; position: absolute; right: -15px; top: 50%; transform: translateY(-50%); } </style> </head> <body> <div id="hide"><span class="out">出來</span></div> <script> window.onload = function() { var hide = document.getElementById("hide"); hide.onmouseover = function() { startMove(0, 10); }; hide.onmouseout = function() { startMove(-200, -10); }; }; var timer = null; // function startMoveout() { // // 防止連續移入元素會生成多個計時器,所以進入之前先清除 // clearInterval(timer); // var hide = document.getElementById("hide"); // timer = setInterval(function() { // if (hide.offsetLeft == 0) { // clearInterval(timer); // } else { // hide.style.left = hide.offsetLeft + 1 + 'px'; // } // }, 17); // } // function startMovein() { // // 防止連續移入元素會生成多個計時器,所以進入之前先清除 // clearInterval(timer); // var hide = document.getElementById("hide"); // timer = setInterval(function() { // if (hide.offsetLeft == -200) { // clearInterval(timer); // } else { // hide.style.left = hide.offsetLeft - 1 + 'px'; // } // }, 17); // } // 將上面的程式碼合併 function startMove(target, speed) { // 防止連續移入元素會生成多個計時器,所以進入之前先清除 clearInterval(timer); var hide = document.getElementById("hide"); timer = setInterval(function() { if (hide.offsetLeft == target) { clearInterval(timer); } else { hide.style.left = hide.offsetLeft + speed + 'px'; } }, 17); } </script> </body> </html>