实现事件来回切换

div

1、新建一个层,点击层,希望层的背景色在蓝色和红色之间切换。




<script type="text/javascript"> function addEVent(obj,type,fn){ var saved=null; //判断是否之前有事件,如果有,保存下来 if(typeof obj['on'+type]=='function'){ saved=obj['on'+type]; } //执行 obj['on'+type]=function(){ if(saved)saved(); fn.call(this); }; } addEVent(window,'load',function(){ var box=document.getElementById('box'); addEVent(box,'click',toBlue); }); function toBlue(){ this.className='blue'; addEVent(this,'click',toRed); } function toRed(){ this.className='red'; addEVent(this,'click',toBlue); } </script>
<body>
<div id="box" class="red">div</div>

</body>
<style type="text/css">
.red{
	100px;
	height:100px;
	background:red;
	}

.blue{
	100px;
	height:100px;
	background:blue;
	}
</style>
原文地址:https://www.cnblogs.com/jiangwenli/p/4891327.html