天天看點

如何讓JavaScript元素運動起來 ?

1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         #div1 {
 8             width: 200px;
 9             height: 200px;
10             background-color: red;
11             position: absolute;
12             left: 0;
13             top: 50px;
14         }
15     </style>
16     <script>
17         window.onload = function () {
18             var div = document.getElementById("div1");
19             setInterval(function () {
20                 div.style.left = div.offsetLeft + 20 + "px";
21             }, 30);
22         }
23     </script>
24 </head>
25 <body>
26     <div id="div1"></div>
27 </body>
28 </html>      

運作效果戳 [這裡]

在<style>元素中,設定#div1元素的 {position:absolute; left:0; top:50px;}。

在<script>中,通過改變元素的left值來使元素運動起來。 這裡需要注意的是offsetLeft傳回的是數值,而style.left設定時需要帶上機關。

MDN中有關于[offsetLeft], [left], [position]更多的資訊,同時我的[部落格]中也有一篇關于offsetLeft的介紹~

轉載于:https://www.cnblogs.com/linxd/p/4540058.html

繼續閱讀