1. 程式人生 > 其它 >動畫函式的簡單封裝

動畫函式的簡單封裝

注意函式需要傳遞2個引數,動畫物件和移動到的距離。

示例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title
> <!-- 動畫裡必須加定位 --> <style> div { position: absolute; left: 0; width: 100px; height: 100px; background-color: pink; } span { position: absolute; top: 150px; display
: block; width: 150px; height: 150px; background-color: purple; } </style> </head> <body> <div></div> <span></span> </body> <script> // 簡單動畫函式封裝 obj目標物件 target目標位置 function animate(obj, target) {
var timer = setInterval(function () { if (div.offsetLeft >= target) { // 停止動畫 本質是停止定時器 clearInterval(timer) } obj.style.left = obj.offsetLeft + 1 + 'px' }, 30) } var div = document.querySelector('div') var span = document.querySelector('span') // 呼叫函式 animate(div, 300) animate(span, 200) </script> </html>