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

如何用JavaScript实现悬停图片时修改表格指定文本颜色?

我好像已经解决了这个问题!不过如果大家有更简洁的实现思路就太棒了!我是JavaScript新手,哈哈


需求说明

  • 我有一张图片和包含文本的表格,希望悬停该图片时,表格中对应列的所有花朵图标文本能改变颜色。
  • 具体目标:悬停「Fig 1 Hover」时,表格里Fig 1列的所有花朵图标变红;悬停「Fig 2 Hover」时,Fig 2列的所有花朵图标变红。

问题重现

单个图标(ID方式)有效代码

最初针对单个图标使用id="sticker3"时,代码能正常工作:

HTML

<span id="sticker3" style="font-size: 30px;margin:0px;line-height:0px;color:#000000;">✿</span>

JavaScript

function upDate(){
    document.getElementById('sticker3').style.color = "#FF0000";
}

function unDo(){
    X = document.getElementById('sticker3');
    X.style.color = "";
    document.getElementById('sticker3').style.color = "#FFFFFF";
}

批量图标(Class方式)失效代码

当把图标改为class="sticker3"并使用getElementsByClassName("sticker3")后,代码无法正常运行:

HTML

<span class="sticker3" style="font-size: 30px;margin:0px;line-height:0px;color:#000000;">✿</span>

JavaScript

function upDate(){
    document.getElementsByClassName('sticker3').style.color = "#FF0000";
}

function unDo(){
    X = document.getElementsByClassName('sticker3');
    X.style.color = "";
    document.getElementsByClassName('sticker3').style.color = "#FFFFFF";
}

完整代码片段

HTML

<table id="table1">
  <thead>
    <tr>
      <th>Name</th>
      <th>Fig 1</th>
      <th>Fig 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td><span class="sticker3"></span></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td><span class="sticker3"></span></td>
    </tr>
    <tr>
      <td></td>
      <td><span class="sticker3"></span></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td><span class="sticker3"></span></td>
    </tr>
    <tr>
      <td></td>
      <td><span class="sticker3"></span></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td><span class="sticker3"></span></td>
    </tr>
  </tbody>
</table>

<div id="hover1" class="hoverbox">Fig 1 Hover</div>
<div id="hover2" class="hoverbox">Fig 2 Hover</div>

CSS

body {
  font-family: sans-serif;
}

table {
  border-collapse: collapse;
}

td,
th {
  border: thin solid lightgray;
  padding: 0.2rem;
}

.sticker3:after {
  content: "✿";
  font-size: 20px;
  margin: 0px;
  line-height: 0px;
  color: #000000;
}

.hoverbox {
  width: 10rem;
  display: inline-block;
  border: thin solid gray;
  background-color: lightyellow;
  margin: 0.5rem;
  padding: 0.5rem;
}

JavaScript

function upDate() {
  document.getElementsByClassName('sticker3').style.color = "#FF0000";
}

function unDo() {
  X = document.getElementsByClassName('sticker3');
  X.style.color = "";
  document.getElementsByClassName('sticker3').style.color = "#FFFFFF";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:57:34