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

计算器hover选择器问题:实现1至=按钮背景色切换

解决CSS计算器按钮hover样式问题

你的问题出在当前的hover选择器上:div.result ~ div:hover ~ div 只会选中被hover元素之后的所有同级按钮,而不会选中被hover的按钮本身。要实现hover时修改当前按钮的背景色,需要调整选择器。

修正后的CSS方案

替换你现有的hover规则,改为直接选中被hover的按钮:

/* 选中.result之后的所有按钮,并设置hover样式 */
div.result ~ div:hover {
  background-color: aquamarine;
}

或者使用:nth-child选择器(更精准地定位从「1」到「=」的按钮,即.panel的第2个及以后的子元素):

.panel div:nth-child(n+2):hover {
  background-color: aquamarine;
}

完整修正后的CSS代码

* {
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  height: 100vh;
  justify-content: center;
  align-items: center;
  font-family: Verdana, Geneva, Tahoma, sans-serif;
}

div.panel {
  display: flex;
  height: 85vh;
  min-width: 500px;
  flex-basis: 60%;
  flex-wrap: wrap;
  align-content: space-between;
  justify-content: space-between;
  background-color: #fff;
}
div.result {
  display: flex;
  height: 15vh;
  padding-right: 50px;
  flex-basis: 100%;
  justify-content: flex-end;
  align-items: center;
  font-size: 50px;
  background-color: #000;
  color: white;
}

div.result ~ div {
  display: flex;
  flex-basis: 30%;
  height: 10vh;
  justify-content: center;
  align-items: center;
  background-color: cadetblue;
  color: white;
  font-size: 40px;
  cursor: pointer;
}

/* 修正后的hover规则 */
div.result ~ div:hover {
  background-color: aquamarine;
}

div div:nth-last-of-type(1),
div div:nth-last-of-type(2) {
  flex-basis: 45%;
}

这样修改后,当你hover任意按钮时,该按钮的背景色会变为aquamarine,而不是其他按钮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:15:33