Python-100-Days/Day21-30/code/web1807/example06.html

62 lines
2.1 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<!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>