1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>在当前显示区范围内实现点不到的小方块</title>
6 <style>
7 div{position:fixed;width:50px;height:50px;
8 background-color:pink;
9 }
10 </style>
11
12 </head>
13 <body>
14 <div id="pop"></div>
15 <script>
16 var game={
17 PSIZE:0,//保存div的大小
18 MAXTOP:0,//保存最大可以top
19 MAXLEFT:0,//保存最大可用left
20 pop:null,//保存主角div
21 init:function(){
22 //查找id为pop的div保存在pop属性中
23 this.pop=document.getElementById("pop");
24 //获取pop计算后的样式中的width,转为浮点数保存在PSIZE属性中
25 this.PSIZE=parseFloat(getComputedStyle(this.pop).width);
26 //计算MAXTOP:文档显示区的高-PSIZE
27 this.MAXTOP=innerHeight-this.PSIZE;
28 //计算MAXLEFT:文档显示区的宽-PSIZE
29 this.MAXLEFT=innerWidth-this.PSIZE;
30 //debugger;
31 debugger;
32 //在0-MAXTOP之间生成随机数,保存在变量rTop中
33 var rTop=Math.floor(Math.random()*(this.MAXTOP+1));
34 //在0-MAXLEFT之间生成随机数,保存在变量rLeft中
35 var rLeft=Math.floor(Math.random()*(this.MAXLEFT+1));
36 //设置pop的top为rTop
37 this.pop.style.top=rTop+"px";
38 //设置pop的left为rLeft
39 this.pop.style.left=rLeft+"px";
40 }
41
42 }
43 game.init();
44 </script>
45
46 </body>
47 </html>