Red or GreenRed How to change color: use buttons-PHP Chinese Network Q&A
How to change color: use buttons
P粉111927962
P粉111927962 2023-09-05 16:38:19
0
1
385

Is there a way for me to write fewer lines of code in this function? I want it to switch between the two colors when you press one of the buttons. The function green() is the exact opposite of red.

red or green

function red() { document.getElementById("header").innerHTML = "red" document.getElementById('header').style.color = "red" document.getElementById('redButton').style.color = "white" document.getElementById('redButton').style.backgroundColor = "red" document.getElementById('greenButton').style.color = "black" document.getElementById('greenButton').style.backgroundColor = "grey" }

P粉111927962
P粉111927962

reply all (1)
P粉254077747

// 缓存经常访问的元素 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; }

Red Or Green

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!