新建一個文件夾,里面包含一張名為star的png格式的圖片。
首先將body的背景設置成黑色
body style="background:#000";
定義一個生成隨機數(shù)的函數(shù)
<script>
function rand(min,max){
? ?time=Math.random()*(min+max)+min;
}
定義一個計時器,每隔一秒則添加一個img元素
setInterval(function(){
創(chuàng)建img元素標簽
? var img=document.createElement("img");
添加圖片
? img.setAttribute("src","star.png");
設置圖片寬度
? img.setAttribute("width",rand(30,100));
設置圖片的位置
img.setAttribute("style","position:absolute;left:"+rand(50,500)+"px;top:rand(50,500)"+"px");
將元素標簽追加到body中
document.body.appChild(img);
獲取body中的元素
var star=document.getElementByTagName("img");
循環(huán)遍歷頁面中的元素
for(var i=0;i<=img.length;i++){
點擊哪個元素也將該元素從頁面中刪除
? img[i].onclick=function(){
? document.body.removeChild(this);
}
}
},1000)
</script>