
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>js实现动图效果</title>
6 <style>
7 #man{
8 position: absolute;
9 left: 20px;
10 height: 50px;
11 }
12 #codingman{
13 position: absolute;
14 left: 20px;
15 top: 250px;
16 }
17 </style>
18 <script>
19 window.onload = function () {
20 //设置定时器不停的切换图片
21 var count = 0;
22 var man = document.getElementById("man");
23 setInterval(function () {
24 man.src = "running/runner"+count+".jpg";
25 count++;
26 if(count == 6){
27 count = 0;
28 }
29 }, 100);
30
31 //一直改变img 的left 变大
32 setInterval(function () {
33 //拿到图片在屏幕上的位置
34 var left = parseInt(getStyle(man,"left"));
35 //计算位置
36 var next = left + 30;
37 //设置边界
38 //window.innerWidth当前窗口的宽度
39 if(next >= window.innerWidth){
40 next = -95;
41 }
42 man.style.left = next+"px";
43 }, 100);
44
45 var countman = 0;
46 var codingman = document.getElementById("codingman");
47 setInterval(function () {
48 codingman.src = "running/running"+countman+".png";
49 countman++;
50 if(countman == 4){
51 countman = 0;
52 }
53 }, 100);
54 }
55
56 //获取style样式的css属性,考虑兼容;ie,火狐/谷歌;
57 function getStyle(parm1,parm2) {
58 return parm1.currentStyle ? parm1.currentStyle[parm2] : getComputedStyle(parm1)[parm2]; //parm1,要改变的元素代替名;parm2,要改变的属性名
59 }
60 </script>
61 </head>
62 <body>
63 <img id="man" src="running/runner0.jpg" width="107px" height="132px"/>
64 <img id="codingman" src="running/runner0.jpg" width="130px" height="97px"/>
65 </body>
66 </html>