改变颜色的方法:使用按钮
P粉111927962
P粉111927962 2023-09-05 16:38:19
[JavaScript讨论组]
<p>有没有办法让我在这个函数中写更少的代码行?我希望当你按下其中一个按钮时,它会在两种颜色之间切换。函数green()是red的完全相反。</p> <pre class="lang-html prettyprint-override"><code>&lt;h1 id=&quot;header&quot;&gt;红色还是绿色&lt;/h1&gt; &lt;button id=&quot;redButton&quot; onclick=&quot;red()&quot;&gt;红色&lt;/button&gt; &lt;button id=&quot;greenButton&quot; onclick=&quot;green()&quot;&gt;绿色&lt;/button&gt; </code></pre> <pre class="brush:php;toolbar:false;">function red() { document.getElementById(&quot;header&quot;).innerHTML = &quot;红色&quot; document.getElementById('header').style.color = &quot;red&quot; document.getElementById('redButton').style.color = &quot;white&quot; document.getElementById('redButton').style.backgroundColor = &quot;red&quot; document.getElementById('greenButton').style.color = &quot;black&quot; document.getElementById('greenButton').style.backgroundColor = &quot;grey&quot; }</pre></p>
P粉111927962
P粉111927962

全部回复(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;
}
<h1 id="header">Red Or Green</h1>
<button id="redButton">Red</button>
<button id="greenButton">Green</button>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号