cari

Rumah  >  Soal Jawab  >  teks badan

Cara menukar warna: gunakan butang

<p>Adakah terdapat cara untuk saya menulis lebih sedikit baris kod dalam fungsi ini? Saya mahu ia bertukar antara dua warna apabila anda menekan salah satu butang. Fungsi green() adalah bertentangan dengan red. </p> <pre class="lang-html prettyprint-override"><code><h1 id="header">merah atau hijau</h1> <button id="redButton" onclick="red()">red</button> <button id="greenButton" onclick="hijau()">hijau</button> </code></pre> <pre class="brush:php;toolbar:false;">function red() { document.getElementById("header").innerHTML = "merah" document.getElementById('header').style.color = "merah" document.getElementById('redButton').style.color = "putih" document.getElementById('redButton').style.backgroundColor = "merah" document.getElementById('Button hijau').style.color = "hitam" document.getElementById('Button hijau').style.backgroundColor = "kelabu" }</pre></p>
P粉111927962P粉111927962472 hari yang lalu479

membalas semua(1)saya akan balas

  • P粉254077747

    P粉2540777472023-09-06 11:09:33

    // 缓存经常访问的元素
    const headerElement = document.getElementById("header");
    const redButton = document.getElementById("redButton");
    const greenButton = document.getElementById("greenButton");
    
    // 为整个文档添加事件监听器,利用事件委托
    document.addEventListener("click", function(event) {
      const targetId = event.target.id;
      
      if (targetId === "redButton") {
        headerElement.innerHTML = "Red";
        headerElement.style.color = "red";
        redButton.classList.add("active-red");
        greenButton.classList.remove("active");
      } else if (targetId === "greenButton") {
        headerElement.innerHTML = "Green";
        headerElement.style.color = "green";
        greenButton.classList.add("active-green");
        redButton.classList.remove("active");
      }
    });
    .active {
      color: white;
    }
    
    .active-red {
      color: white;
      background-color: red;
    }
    
    .active-green {
      color: black;
      background-color: grey;
    }
    <h1 id="header">Red Or Green</h1>
    <button id="redButton">Red</button>
    <button id="greenButton">Green</button>

    balas
    0
  • Batalbalas