<html>
<head>
	<title>changeColor</title>
</head>
<body>
<div id="colorBox1" class="colorBox"></div>
<div id="colorBox2" class="colorBox"></div>
</body>
</html>
.colorBox {
  width: 200px;
  height: 200px;
  margin: 20px;
  background-color : rgb(100, 200, 100);
  cursor: pointer;
}
// 获取元素的id值
function getId(id) {
	return document.getElementById(id);
}

// 事件绑定器
// 参数:target为DOM对象,event为事件名称(不带"on"),callback为接收事件处理的函数
function bindEvent(target, event, callback) {
	if(window.addEventListener) {
		return target.addEventListener(event, callback, false);
	}else if(target.attachEvent) {
		// addEventListener不能兼容IE6-8,需要使用attachEvent进行事件绑定
		return target.attachEvent("on"+event, function() {
			callback.apply(target);
		});
	}
}

// 随机颜色生成器
function changeColor() {
	// 创造随机颜色
	function randomColor() {
		// 这里使用rgb颜色值
		var colorVal = "rgb(";
		for(i = 0; i < 3; i++) {

			colorVal += Math.round(250*Math.random());
			if (i < 2) {
				colorVal += ",";
			}
		}
		colorVal += ")";
		return colorVal;

	}

	this.style.backgroundColor = randomColor();
}

// 获取变色元素div
var colorBox1 = getId("colorBox1");
var colorBox2 = getId("colorBox2");
// 对变色元素div绑定changecolor()事件
bindEvent(colorBox1, "click", changeColor, false);
bindEvent(colorBox2, "click", changeColor, false);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.