JS實現的隨機顯示圖片


 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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM