example06.html 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <style>
  7. #buttons>button {
  8. border: none;
  9. outline: none;
  10. width: 120px;
  11. height: 40px;
  12. font: 22px/40px Arial;
  13. background-color: red;
  14. color: white;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="buttons">
  20. <button><input type="checkbox">苹果</button>
  21. <button><input type="checkbox">香蕉</button>
  22. <button><input type="checkbox">草莓</button>
  23. <button><input type="checkbox">蓝莓</button>
  24. <button><input type="checkbox">榴莲</button>
  25. <button><input type="checkbox">西瓜</button>
  26. <button><input type="checkbox">芒果</button>
  27. <button><input type="checkbox">柠檬</button>
  28. </div>
  29. <script>
  30. var buttons = document.querySelectorAll('#buttons>button');
  31. for (var i = 0; i < buttons.length; i += 1) {
  32. buttons[i].firstChild.addEventListener('click', function(evt) {
  33. var checkbox = evt.target || evt.srcElement;
  34. if (checkbox.checked) {
  35. checkbox.parentNode.style.backgroundColor = 'lightseagreen';
  36. } else {
  37. checkbox.parentNode.style.backgroundColor = 'red';
  38. }
  39. evt.stopPropagation();
  40. });
  41. buttons[i].addEventListener('click', function(evt) {
  42. // 通过事件对象的target属性可以获取事件源(谁引发了事件)
  43. // 但是有的浏览器是通过srcElement属性获取事件源的
  44. // 可以通过短路或运算来解决这个兼容性问题
  45. var button = evt.target || evt.srcElement;
  46. // 当获取到一个元素之后可以通过它的属性来获取它的父元素、子元素以及兄弟元素
  47. // parentNode - 父元素
  48. // firstChild / lastChild / children - 第一个子元素 / 最后一个子元素 / 所有子元素
  49. // previousSibling / nextSibling - 前一个兄弟元素 / 后一个兄弟元素
  50. var checkbox = button.firstChild;
  51. checkbox.checked = !checkbox.checked;
  52. if (checkbox.checked) {
  53. button.style.backgroundColor = 'lightseagreen';
  54. } else {
  55. button.style.backgroundColor = 'red';
  56. }
  57. });
  58. }
  59. </script>
  60. </body>
  61. </html>