本文實例講解了javascript實現(xiàn)隨機顯示星星特效的詳細代碼,具體內容如下
<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>無標題文檔</title><script type="text/javascript">//定義全局變量var img_width_min = 15;var img_width_max = 80;var x_left = 0;var x_right = 0;var y_top = 0;var y_bottom = 0;//定義初始化的函數(shù)function init(){ document.body.bgColor = "#000"; x_right = window.innerWidth - img_width_max; y_bottom = window.innerHeight - img_width_max; //定時器 setInterval("showStar()",1000);}//顯示星星function showStar(){ //創(chuàng)建一個圖片 var node_img = document.createElement("img"); //隨機圖片大小和隨機坐標 var width = getRandom(img_width_min,img_width_max); var x = getRandom(x_left,x_right); var y = getRandom(y_top,y_bottom); //增加src的屬性 node_img.setAttribute("src","images/xingxing.gif"); //增加style屬性 var style = "position:absolute;left:"+x+"px;top:"+y+"px;"; style += "width:"+width+"px;"; node_img.setAttribute("style",style); //增加一個onclick事件屬性 node_img.setAttribute("onclick","removeImg(this)"); //將圖片追加到<body>元素下 document.body.appendChild(node_img);}function removeImg(obj){ document.body.removeChild(obj);}function getRandom(min,max){ return Math.floor(Math.random()*(max-min)+min);}</script></head><body onload="init()"></body></html>希望本文所述對大家的javascript程序設計有所幫助。
新聞熱點
疑難解答