计算器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
相关产品推荐
相关产品推荐

