1:获取css的属性样式的兼容写法 function getstyle(DOM,name){ if(DOM.currentStyle){ IE的兼容 return DOM.currentStyle[name]; }else{其他浏览器的兼容 return getComputedStyle(DOM,false)[name]; } } 什么是物体运动? 就是改变物体top/right/bottom/left、值
运动的核心? 1:布局中div必须定位 2:js中必须用到定时器小球
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #box{ width: 100px; height: 100px; background: red; border-radius:50% ; position: absolute; } </style> </head> <body> <button onclick="btn()">开始</button> <div id="box"></div> </body> <script type="text/javascript"> //连续点击开始按钮才生一个问题,会让小球加速度,小球动起了会越来越快 var odiv=document.getElementById('box'); var timer; function btn(){ clearInterval(timer);//解决小球加速问题 timer=setInterval(function(){ if(odiv.offsetLeft>=1500){ clearInterval(timer); }else{ odiv.style.left=odiv.offsetLeft+10+'px'; } },50) } </script> </html>多个小球
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #box{ width: 100px; height: 100px; background: red; border-radius:50% ; position: absolute; } #box1{ width: 100px; height: 100px; background: red; border-radius:50% ; position: absolute; top:150px; } #box2{ width: 100px; height: 100px; background: red; border-radius:50% ; position: absolute; top:280px; } </style> </head> <body> <button onclick="btn()">开始</button> <div id="box"></div> <div id="box1"></div> <div id="box2"></div> </body> <script type="text/javascript"> //对案例中重复的代码进行封装 //封装代码的思路 //1对相同的代码,提取出来,用函数包裹 //2对相同元素,提取出来,用函数的参数代表 //3改错 var odiv=document.getElementById('box'); var odiv1=document.getElementById('box1'); var odiv2=document.getElementById('box2'); var timer; var timer1; var timer2; function btn(){ clearInterval(timer); clearInterval(timer1); move(timer,odiv) move(timer1,odiv1) move(timer2,odiv2) } function move(tim,obj){ tim=setInterval(function(){ if(obj.offsetLeft>=1500){ clearInterval(tim); }else{ obj.style.left=obj.offsetLeft+10+'px'; } },50) } </script> </html>小球来回移动
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #warp{ width: 800px; height: 300px; border: 1px solid red; margin: auto; position: relative; } #box{ width: 100px; height: 100px; background: red; border-radius:50% ; position: absolute; top:200px; } </style> </head> <body> <div id="warp"> <div id="box"></div> </div> </body> <script type="text/javascript"> var owarp=document.getElementById('warp'); var odiv=document.getElementById('box'); var timer; var speed=5; timer=setInterval(function(){ if(odiv.offsetLeft>=700){ odiv.style.left=odiv.offsetLeft+speed+'px'; }else{ odiv.style.left=odiv.offsetLeft-speed+'px'; } },50) </script> </html>