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

咨询:如何实现鼠标悬停/移出div时切换内容显示与样式?

实现悬停切换文本与按钮的交互效果

核心修改要点

  • 原代码获取按钮的方法错误:getElementsByTagName仅支持标签名参数,需替换为querySelectorAll来通过CSS选择器定位按钮
  • 直接嵌入div的文本“a”无法单独控制显示,需用<span>包裹,实现独立的显示/隐藏逻辑
  • 修正JS中颜色设置与需求不符的问题:悬停时div文字颜色应为黑色,移出时恢复白色
  • 调整CSS布局,让元素对齐更合理,避免默认边距影响效果

修正后的完整代码

HTML

<section>
  <div id="firstItem">
    <div id="a">
      <span class="default-text">a</span>
      <button>a1</button>
      <button>a2</button>
      <button>a3</button>
      <button>a4</button>
      <button>a5</button>
      <button>a6</button>
    </div>
    <div class="b">b</div>
    <div class="b">c</div>
    <div class="b">d</div>
    <div class="b">e</div>
    <div class="b">f</div>
    <div class="b">g</div>
    <div class="b">h</div>
  </div>
  <div id="frame"></div>
</section>

CSS

* {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

section {
  display: flex;
}

#firstItem {
  width: 10%;
  height: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: repeat(6, 1fr);
}

#frame {
  width: 90%;
  height: 100%;
}

section #firstItem div {
  color: #FFFFFF;
  background-color: #000000;
  border: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

section #firstItem #a {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: repeat(3, 1fr);
}

section #firstItem #a button {
  display: none;
  background-color: #56F1FF;
  color: #000000;
  width: auto;
  height: auto;
  padding: 5px 10px;
}

JavaScript

const aDiv = document.getElementById("a");
const defaultText = aDiv.querySelector(".default-text");
const buttons = aDiv.querySelectorAll("button");

aDiv.addEventListener('mouseover', () => {
  // 隐藏默认文本,显示按钮
  defaultText.style.display = "none";
  buttons.forEach(btn => btn.style.display = "flex");
  // 修改背景和文字颜色
  aDiv.style.backgroundColor = "#56F1FF";
  aDiv.style.color = "#000000";
});

aDiv.addEventListener('mouseout', () => {
  // 显示默认文本,隐藏按钮
  defaultText.style.display = "flex";
  buttons.forEach(btn => btn.style.display = "none");
  // 恢复原背景和文字颜色
  aDiv.style.backgroundColor = "#000000";
  aDiv.style.color = "#FFFFFF";
});

效果验证

  • 鼠标悬停#a区域:文本“a”隐藏,所有按钮显示,div背景变为浅蓝色#56F1FF,文字颜色切换为黑色
  • 鼠标移出#a区域:文本“a”重新显示,按钮隐藏,div恢复黑色背景与白色文字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:40:23