如何让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的介绍~

posted @ 2015-05-30 11:19  林大勇  阅读(858)  评论(0编辑  收藏  举报