You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击颜色选择div元素,修改用户输入文本的字体颜色

你现在的问题是不管点击哪个颜色圆点,文本只会变成第一个圆点的颜色——这是因为document.querySelector(".dot")只会选取页面中第一个class为dot的元素,所以每次都取的是第一个圆点的背景色。

下面是修复后的代码:

修改后的HTML

<label id="color" for="coloris">Coloris :<span class="haut">V</span><span>V</span></label>
<div id="coloris">
  <div class="dot" title="RAL 9018 - Blanc Papyrus" style="background-color:#d4dbd9" onclick="changeColor(this)">
    <input type="radio" value="RAL 9018 - Blanc Papyrus" name="RAL">
  </div>
  <div class="dot" title="RAL 9016 - Blanc Signalisation" style="background-color:#f6f8fa" onclick="changeColor(this)">
    <input type="radio" value="RAL 9016 - Blanc Signalisation" name="RAL">
  </div>
  <div class="dot" title="RAL 9011 - Noir Graphite" style="background-color:#212123" onclick="changeColor(this)">
    <input type="radio" value="RAL 9011 - Noir Graphite" name="RAL">
  </div>
  <div class="dot" title="RAL 9010 - Blanc Pur" style="background-color:#f4f5ef" onclick="changeColor(this)">
    <input type="radio" value="RAL 9010 - Blanc Pur" name="RAL">
  </div>
</div>

修改后的JavaScript

function changeColor(clickedDot){
  // 设置文本颜色为当前点击圆点的背景色
  document.getElementById("showtext").style.color = clickedDot.style.backgroundColor;
  // 可选:同时选中当前圆点内的单选框
  clickedDot.querySelector('input').checked = true;
}

核心修改说明

  1. 把onclick的参数从'#showtext'改成this,直接将当前点击的圆点元素传递给函数
  2. 函数内通过传入的clickedDot获取对应背景色,不再固定取第一个圆点的样式

内容的提问来源于stack exchange,提问作者Mathieu soumier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:22:13