<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>星星案例</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<style type="text/css">
body{
margin: 0px;
height: 300px;
}
.button{
margin-left: 100px;
margin-top: 30px;
}
.button input {
color: blue;
font-size: 15px;
}
#time{
color: blue;
font-size: 15px;
}
#num{
color: blue;
font-size: 15px;
}
#jindu{
width: 100px;
height: 20px;
border:1px solid red;
display: inline-block;
}
#inner{
height: 20px;
display: inline-block;
}
</style>
<script type="text/javascript">
var dingshiqi;
var counter = 0;
var second = 0;
window.onload = init;
function init(){
// document.body.style.backgroundColor="black";
}
function showImg(){
counter++;
second++;
//在网页上点击出现星星
var obj=document.createElement("img");
obj.src="xingxing.gif";
//设置图像大小 20---60
var w = Math.random()*((60-20)+1)+20
obj.width=w;
//设置图像的位置
var x = Math.random()*(1440-20+1)+20;//x需要随即出现 20———1440
var y = Math.random()*(900-20+1)+20;//y需要随即出现 20----900
obj.style.position="absolute";
obj.style.left = x + "px";
obj.style.top = y + "px";
if(counter>20){
return;
}
document.body.appendChild(obj);
obj.onclick = remove;
//更新进行时间
showTotalTime();
//更新星星个数
showNum();
//更新进度
showJindu();
}
function start(){
//开启定时器
dingshiqi = window.setInterval("showImg()",300);
}
function stop(){
window.clearInterval(dingshiqi);
}
function remove(){
this.parentNode.removeChild(this);
counter--;
//更新星星个数
showNum();
//更新进度
showJindu();
}
function showNum(){
var obj = document.getElementById("num");
obj.innerHTML = counter+ "个";
if(counter>20){
stop();
return;
}
}
function showTotalTime(){
var obj = document.getElementById("time");
obj.innerHTML = second + "秒";
}
function showJindu(){
var obj = document.getElementById("inner");
obj.style.width = counter * 5+"px";
obj.style.backgroundColor = "red";
}
</script>
</head>
<body >
<div class="button">
<span id="num">个数</span>
<input type="button" name="start" value="开始" οnclick="start()">
<input type="button" name="stop" value="暂停" οnclick="stop()">
<span id="time">时间</span>
<span id="jindu"><span id="inner"></span></span>
</div>
</body>
</html>
这里用到的知识点有:
给对象绑定事件:
格式:对象.οnclick=函数名;注意:函数名后面不加括号
在绑定事件中,this是可以直接用的.this.parentNode就是获得this的父节点
删除标签
注意:当想要删除标签的时候,必须找到这个对象的上级标签(父节点)