example06.html 2.06 KB
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#buttons>button {
				border: none;
				outline: none;
				width: 120px;
				height: 40px;
				font: 22px/40px Arial;
				background-color: red;
				color: white;
			}
		</style>
	</head>
	<body>
		<div id="buttons">
			<button><input type="checkbox">苹果</button>
			<button><input type="checkbox">香蕉</button>
			<button><input type="checkbox">草莓</button>
			<button><input type="checkbox">蓝莓</button>
			<button><input type="checkbox">榴莲</button>
			<button><input type="checkbox">西瓜</button>
			<button><input type="checkbox">芒果</button>
			<button><input type="checkbox">柠檬</button>
		</div>
		<script>
			var buttons = document.querySelectorAll('#buttons>button');
			for (var i = 0; i < buttons.length; i += 1) {
				buttons[i].firstChild.addEventListener('click', function(evt) {
					var checkbox = evt.target || evt.srcElement;
					if (checkbox.checked) {
						checkbox.parentNode.style.backgroundColor = 'lightseagreen';
					} else {
						checkbox.parentNode.style.backgroundColor = 'red';
					}
					evt.stopPropagation();
				});
				buttons[i].addEventListener('click', function(evt) {
					// 通过事件对象的target属性可以获取事件源(谁引发了事件)
					// 但是有的浏览器是通过srcElement属性获取事件源的
					// 可以通过短路或运算来解决这个兼容性问题
					var button = evt.target || evt.srcElement;
					// 当获取到一个元素之后可以通过它的属性来获取它的父元素、子元素以及兄弟元素
					// parentNode - 父元素
					// firstChild / lastChild / children - 第一个子元素 / 最后一个子元素 / 所有子元素
					// previousSibling / nextSibling - 前一个兄弟元素 / 后一个兄弟元素
					var checkbox = button.firstChild;
					checkbox.checked = !checkbox.checked;
					if (checkbox.checked) {
						button.style.backgroundColor = 'lightseagreen';
					} else {
						button.style.backgroundColor = 'red';
					}
				});
			}
		</script>
	</body>
</html>