<html>
<head>
<title>随機顯示小星星</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript">
/*
執行個體:随機顯示小星星
(1) 網頁背景色為黑色
(2)建立圖檔節點,追加到body父節點。
(3)圖檔随機大小
(4)圖檔的随機定位坐标(x,y)
(5)定時器
(6)網頁加載完成,星星開始顯示
(7)确定星星顯示的範圍,跟window的寬高一樣
(8)單擊星星,星星消失
*/
// 網頁加載完成
window.onload = init;
function init()
{
// 網頁背景色
document.body.bgColor = "#000";
// 定時器:1s顯示一個星星
window.setInterval("star()",);
}
// 動畫主函數
function star()
{
//建立星星節點
var imgObj = document.createElement("img");
// 添加src屬性
imgObj.setAttribute("src", "images/xingxing.gif");
// 添加width
var width = getRandom(, );
imgObj.setAttribute("width", width);
// 添加style屬性(行内樣式)
var x = getRandom(,window.innerWidth);
var y = getRandom(, window.innerHeight);
imgObj.setAttribute("style", "position:absolute;left:"+x+"px; top:" + y + "px;");
// 将圖檔節點,挂再父節點下
document.body.appendChild(imgObj);
// 單擊星星, 星星消失
// this 代表目前對象,this隻能在函數内使用
imgObj.setAttribute("onClick", "missStar(this)");
}
// 星星消失
function missStar(obj)
{
document.body.removeChild(obj);
}
// 求随機數
function getRandom(min, max)
{
var random = Math.random()*(max-min)+min;
random = Math.floor(random);
return random;
}
</script>
</head>
<body>
</body>
</html>
星星的圖檔如下圖所示

具體效果
代碼下載下傳:http://download.csdn.net/download/williamgavin/10217889