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

如何设置仅当按钮hover时触发伪元素的悬停效果

解决方案

问题出在伪元素默认会响应鼠标事件,哪怕它在按钮视觉范围之外,鼠标悬停在它上面时也会触发按钮的:hover状态。要让伪元素的绿色背景仅在按钮本体被hover时触发,只需给伪元素添加pointer-events: none;属性,让它不接收任何鼠标事件。

修改后的CSS代码:

button {
    box-sizing: border-box;
    background-color: blue;
    padding: 10px 20px;
    color: white;
    position: relative;
}

button::before {
    content: '';
    position: absolute;
    background-color: transparent;
    height: 20px;
    width: 100%;
    left: 0;
    bottom: -30px;
    pointer-events: none; /* 添加这一行 */
}

button:hover::before {
    background-color: green;
}

对应的HTML保持不变:

<button>
I am a button
</button>

设置完成后,只有当鼠标悬停在蓝色的按钮区域时,下方的伪元素才会变为绿色;鼠标移到伪元素区域但未hover按钮时,不会触发任何效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:35:25