为何按钮选中后Hover(悬停)效果失效?
问题原因及解决方案
原因分析
问题核心是内联样式的优先级远高于CSS类选择器。当你点击新菜单项时,会通过JS给之前选中的按钮添加style.backgroundImage = "none"的内联样式,这个样式直接写在元素的HTML标签上,优先级比.btn-group .button:hover这个类选择器高得多。所以当你再次悬停这个按钮时,hover定义的渐变背景样式无法覆盖内联的backgroundImage: none,自然看不到渐变效果。
解决方案
放弃直接操作内联样式,改用CSS类来管理按钮的选中/未选中状态,这样能避免优先级冲突,让hover样式正常生效。
修改后的完整代码
<!DOCTYPE html> <html> <head> <style> .menu{ background-color: cornflowerblue; } .btn-group .button { background-color: #4CAF50; /* Green */ border: 1px solid green; color: white; padding: 15px 32px; text-align: center; text-decoration: none; font-size: 16px; cursor: pointer; width: 150px; display: block; } .btn-group .button:hover { background-image: linear-gradient(to bottom, rgb(92, 88, 46), rgb(247, 229, 41), rgb(92,88,46)); color: red; } /* 选中状态样式 */ .btn-group .button.active { color: rgb(17, 15, 15); background-image: linear-gradient(to bottom, rgb(92, 88, 46), rgb(247, 229, 41), rgb(92,88,46)); } /* 未选中状态样式 */ .btn-group .button.inactive { background-color: rgb(33, 31, 31); color: rgb(255, 234, 0); background-image: none; } </style> </head> <body onload="fnOnLoad()"> <div class="menu"> <div class="btn-group"> <button id="WhatsNew" onclick="btnClick('WhatsNew')" class="button">What's New</button> <button id="Button1" onclick="btnClick('Button1')" class="button">Button1</button> <button id="Button2" onclick="btnClick('Button2')" class="button">Button2</button> <button id="Button3" onclick="btnClick('Button3')" class="button">Button3</button> <button id="Button4" onclick="btnClick('Button4')" class="button">Button4</button> </div> </div> <script> let curBtn = document.getElementById("WhatsNew"); function fnOnLoad(){ curBtn.classList.add("active"); } function btnClick(btnName){ const newBtn = document.getElementById(btnName); // 切换当前按钮状态 curBtn.classList.remove("active"); curBtn.classList.add("inactive"); // 切换新按钮状态 newBtn.classList.remove("inactive"); newBtn.classList.add("active"); curBtn = newBtn; } </script> </body> </html>
说明
通过.active和.inactive两个类来管理按钮状态,所有样式都由CSS控制,不会产生内联样式覆盖类样式的问题。由于.btn-group .button:hover和.btn-group .button.inactive的优先级相同,当按钮悬停时,hover伪类的样式会自动覆盖未选中状态的样式,渐变效果就能正常显示了。
内容的提问来源于stack exchange,提问作者Alan
相关产品推荐
相关产品推荐

