一、成果展示
二、代码
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Counter</title> <!-- styles --> <link rel="stylesheet" href="styles.css" /> </head> <body> <main> <div class="container"> <h1>Counter</h1> <span id = "value">0</span> <div class="button-container"> <button class="btn decrease">decrease</button> <button class="btn set">reset</button> <button class="btn increase">increase</button> <!--输入.button, 直接显示<div class="button"></div>-->> </div> </div> </main> <!-- javascript --> <script src="app.js"></script> </body> </html>
Js代码
//set initial count let count = 0; //select value and buttons const value = document.querySelector('#value') const btns = document.querySelectorAll(".btn") btns.forEach(function(btn){ //这里有一个function btn.addEventListener('click',function(e){ //这里有一个function const styles = e.currentTarget.classList if(styles.contains('decrease')){ count--; } else if(styles.contains('increase')){ count++; } else{ count = 0; } if(count>0){ value.style.color = "green"; } if(count<0){ value.style.color = "red"; } if(count==0){ //这里是== value.style.color = "#222"; } value.textContent = count; }); });
https://www.youtube.com/watch?v=3PHXvlpOkf4