利用 SCSS 變數來設定背景顏色可以省去不少力氣,別再做個傻傻的碼農了^^ HTML: <div>AAAAA</div> <div>AAAAA</div> <div>AAAAA</div> <div>AAAAA</div> <div>AAAAA</div> SCSS: $colors : (1: #664454, 2: yellow, 3: #00ff75, 4: #985544, 5: #665566); @for $i from 1 through 5 { div:nth-child(#{$i}){ text-align: center; background-color: map-get ( $colors , $i); } }
這裡利用 forEach 及加入 function toggleOpen 來改變所有子元素字體大小顏色,只要一旦在文字上按下,字體會變大及改變顏色。 HTML: <div class="panels"> <div class="panel panel1">123</div> <div class="panel panel2">123</div> <div class="panel panel3">123</div> <div class="panel panel4">123</div> <div class="panel panel5">123</div> </div> CSS: . tyy { color: red; font-size:80px; } JavaScript: const panels = document.querySelectorAll('.panel'); function toggleOpen () { this.classList.toggle('tyy'); // 或可以直接寫成 this.style.color = "red"; this.style.fontSize = "80px"; this.style.backgroundColor = "green"; } panels.forEach(panel => panel.addEventListener('click', toggleOpen ));