JS小Demo: 点击Body 创建DIV, 点击DIV删除

给小朋友做的演示
三个兼容主流浏览器的公共方法
addEvent
removeEvent
stopEventPropagation


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "  http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
body{padding:0px;margin:0px;color:green;font-weight:bold;text-align: center;font-size:40px;}
div{ height:100px;width:100px;background:red;margin:5px 5px;float:left;_display:inline;}
</style>
<script type="text/javascript">
var index = 0;
function createDiv(){
	var div = document.createElement("div");
	var divData = document.createTextNode("");
	divData.nodeValue = index ++;
	div.appendChild(divData);
	
	addEvent(div, "click", function(e){
		document.body.removeChild(div);
		stopEventPropagation(e || event);
	});
	
	document.body.appendChild(div);
}

addEvent(document, 'click', createDiv);

function addEvent(elem, eventName, handler) {
  if (elem.attachEvent) {
    elem.attachEvent("on" + eventName, function(){
                    handler.call(elem)});
  } else if (elem.addEventListener) {
    elem.addEventListener(eventName, handler, false);
  }
}
function removeEvent(elem, eventName, handler) {
  if (elem.detachEvent) {
    elem.detachEvent("on" + eventName, function(){
                    handler.call(elem)});
  } else if (elem.removeEventListener) {
    elem.removeEventListener(eventName, handler, false);
  }
}
function stopEventPropagation(e){
	if(e.stopPropagation){
		e.stopPropagation();
	}else{
		e.cancelBubble=true;
	}
}
</script>
</head>
<body>
</body>
</html>
 
效果:


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值