日期:2014-05-16  浏览次数:20395 次

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>
?
效果:


?