1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 2 "http://www.w3.org/TR/xhtml1/TDT/xhtml1-strit.dtd">
 3 <html>
 4 <head>
 5 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
 6 <title>随机显示小星星</title>
 7 <script type="text/javascript">
 8 //随机显示小星星:
 9 /*        
10     1,网页背景色是黑色
11     2,创建图标节点,追加到<body>父节点
12     3,图片大小随机
13     4,图片坐标随机
14     5,定时器
15     6,网页加载完成,开始星星
16     7,星星显示的范围,跟窗口的宽高一样.(0,window.innerWidth)
17     8,点击星星,星星消失
18 */
19 //网页加载完成 调用一个函数
20 window.onload=function(){
21 //更改网页背景色
22 document.body.bgColor="#000"
23 //定时器 一秒钟显示一个星星 一秒钟调用star一次
24 window.setInterval("star()",1000);
25 }
26 //动画主函数
27 function star(){
28     //创建图片节点
29     var imgObj = document.createElement("img");
30     //添加src属性
31     imgObj.setAttribute("src","images/lele.jpg");
32     //添加width属性 getRandom()随机数函数
33     var width = getRandom(20,120);
34     imgObj.setAttribute("width",width);
35 
36     //添加层叠样式表属性(style属性  行内样式)
37     var x = getRandom(0,window.innerWidth);
38     var y = getRandom(0,window.innerHeight);
39     //设置坐标 x y 为未知数
40     imgObj.setAttribute("style","position:absolute;left:"+x+"px;top:"+y+"px;");
41     
42     //添加onclick事件属性
43     //this 代表当前对象,this是一个对象,只能在函数内使用
44     imgObj.setAttribute("onclick","removeImg(this)");
45     //将图片节点,挂载到<body>的父节点下
46     document.body.appendChild(imgObj);
47 }
48 
49 //函数:求随机数函数
50 function getRandom(min,max){
51     var random = Math.random()*(max-min)+min;
52     //向下取整
53     random = Math.floor(random);
54     //返回结果
55     return random;
56 
57 }
58 //函数:删除节点
59 function removeImg(obj){
60     document.body.removeChild(obj);
61     
62 }
63 </script>
64 
65 <style type="text/css">
66 
67 </style>
68 
69 </head>
70 <body>
71 
72 
73 </body>
74 </html>