修复Drop-down列表异常触发:光标未悬停按钮却显示下拉
问题
我的下拉列表仅应在悬停于"Text-generative AI"按钮时显示,但目前光标移至按钮左侧任意位置时,下拉列表就会出现。按钮未交互时状态正常,预期仅悬停按钮时显示下拉列表,请问如何修复该问题?
相关代码
HTML
<!DOCTYPE html> <html> <link rel = "stylesheet" href = "style.css"> <head> <title>Productivity Tools</title> </head> <body> <h1>TECH TEAM <img src = "imgs/ebmnhs_logo.jpg" style = "position:relative; left:1200px;" height = "50"></h1> <hr> <div class = "dropdown"> <button>Text-generative AI</button> <div class = "content"> <a href = "https://chat.openai.com/" target = _blank>ChatGPT</a> <a href = "https://bard.google.com/" target = _blank>Bard</a> </div> </div> </body> </html>
CSS
.dropdown button{ background-color: darkgrey; /* button color */ color: white; /* font color */ padding: 10px 10px; cursor: pointer; } /* .dropdown:hover button{ background-color: grey; } */ .dropdown a{ display: block; color: black; /* font color */ text-decoration: none; /* to remove underline */ padding: 10px 10px; } .dropdown .content{ display: none; position: absolute; background-color: lightgray; min-width: 90px; } .dropdown:hover .content{ display: block; }
修复方案
问题根源是.dropdown作为块级元素默认占据整行宽度,光标悬停在按钮左侧的空白区域时,实际是触发了容器的hover事件。只需修改两处CSS即可解决:
- 让
.dropdown仅包裹按钮宽度,避免占据整行:给.dropdown添加display: inline-block; - 将下拉触发逻辑绑定到按钮本身,同时保证鼠标移至下拉列表时不消失:替换原hover规则为针对按钮和下拉列表的hover监听
修改后的完整CSS代码:
.dropdown { display: inline-block; /* 限制容器仅包裹按钮宽度 */ } .dropdown button{ background-color: darkgrey; /* button color */ color: white; /* font color */ padding: 10px 10px; cursor: pointer; } /* .dropdown:hover button{ background-color: grey; } */ .dropdown a{ display: block; color: black; /* font color */ text-decoration: none; /* to remove underline */ padding: 10px 10px; } .dropdown .content{ display: none; position: absolute; background-color: lightgray; min-width: 90px; } /* 仅按钮hover时显示下拉,且下拉列表hover时保持显示 */ .dropdown button:hover + .content, .dropdown .content:hover { display: block; }
修改后只有悬停按钮时才会触发下拉,同时鼠标移至下拉列表内时列表不会消失,保证交互连贯性。
内容的提问来源于stack exchange,提问作者Yuurei
相关产品推荐
相关产品推荐

