请将代码保存成html格式的文件,然后用谷歌或者火狐浏览器打开即可看见效果,提醒:球是可以点击的哦!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script> window.onload=function(){ var oBall=document.getElementById('aball'), oBody=document.getElementById('body'), oDiv=document.getElementById('div'); // 设置运动初始值 var ixspeed=0; var iyspeed=0; var ixmove=10; var iymove=10; function move() { // 动态获取浏览器宽度 减去200不让球体超出浏览器 var sWidth= document.body.clientWidth-200; // 设置固定高度 限制球体运动边界 var sHeight= 550; ixspeed+=ixmove; iyspeed+=iymove; if (ixspeed>sWidth) { ixmove=-10; // 重置位置 ixspeed=sWidth; // 改变浏览器背景颜色 oBody.style.backgroundColor='red'; oBall.value='快来点我呀'; } if(ixspeed<0){ ixmove=10; //重置位置 ixspeed=0; // 改变浏览器背景颜色 oBody.style.backgroundColor='black'; oBall.value='你咋点不到我'; } if (iyspeed>sHeight) { iymove=-10; // 重置位置 iyspeed=sHeight; // 改变浏览器背景颜色 oBody.style.backgroundColor='pink'; oBall.value='损色'; } if(iyspeed<0){ iymove=10; // 重置位置 iyspeed=0; // 改变浏览器背景颜色 oBody.style.backgroundColor='green'; oBall.value='就不让你点'; } oBall.style.left=ixspeed+'px'; oBall.style.top=iyspeed+'px'; } function theTimer() { var oTimer=setInterval(move,30); } theTimer(); oBall.onclick=function(){ alert('被你抓到了'); } } </script> <style> .ball{ padding: 0px; border: 0px; outline: none; width: 200px; height: 200px; font-size: 40px; color: aqua; background-color: gold; border-radius: 100px; /* 绝对定位不占用位置漂浮 */ position: absolute; } .body{ background-color: deepskyblue; } .box2{ /* 设置球体运动的宽度与范围是永远等于浏览器的宽度,这样即使浏览器缩小,也会正常运行 */ width: 100%; /* 此处可以不设置高度,因为上面JS语句中已经限制了球体运动范围 */ /* height: 550px; */ background-color: red; } </style> </head> <body id="body" class="body"> <div class="box2" id="div"> <!-- 定义一个按钮 --> <input class="ball" id="aball" type="button" value="来抓我啊"> </div> </body> </html>仅为学习之余练习使用,请忽略游戏效果。