移动端CSS按钮hover下划线消失问题求助
修复移动端按钮下划线动画不显示的问题
问题核心是移动端没有桌面端的鼠标hover事件,用户通过触摸点击交互时,对应的CSS触发伪类是:active;同时为了兼容键盘导航场景,还需要加上:focus伪类,把下划线动画的触发条件从仅hover扩展到这两种状态即可解决问题。
修复后的CSS代码
修改下划线动画及箭头的触发规则,同时支持:hover、:active和:focus状态:
.button { border: none; background: none; margin-top: 9.5vh; cursor: pointer; /* 保留焦点指示器,提升无障碍体验 */ outline-offset: 2px; } /* Button text */ .button span { letter-spacing: 0.2em; font-size: 1.1vw; font-weight: 500; padding-right: 0.8vw; text-transform: uppercase; } /* Button arrow */ .button svg { height: 0; width: 0; } .button:hover svg, .button:active svg, .button:focus svg { transform: translateX(0); } .button:active svg { transform: scale(0.9); } /* Underline animation on hover */ .hover-underline-animation { position: relative; padding-bottom: 0.5em; } .hover-underline-animation:after { content: ''; position: absolute; width: 85%; transform: scaleX(0); height: 0.15em; bottom: 0; left: 0; transform-origin: bottom right; transition: transform 0.25s ease-out; background-color: black; } .button:hover .hover-underline-animation:after, .button:active .hover-underline-animation:after, .button:focus .hover-underline-animation:after { transform: scaleX(1); transform-origin: bottom left; }
额外修正点
原HTML中onclick存在语法错误,多余了一个分号,修正后代码:
<button id="google" class="button" onclick="window.location.href='https://www.google.com'"> <span id="github" class="hover-underline-animation">Google</span> <svg viewBox="0 0 46 16" xmlns="http://www.w3.org/2000/svg" id="arrow-horizontal"> <path fill="currentColor" transform="translate(30)" d="M8,0,6.545,1.455l5.506,5.506H-30V9.039H12.052L6.545,14.545,8,16l8-8Z" data-name="Path 10" id="Path_10"></path> </svg> </button>
原理说明
- 桌面端:鼠标悬停触发
:hover伪类,正常显示下划线动画。 - 移动端:触摸点击时触发
:active伪类,按钮同时获得焦点触发:focus伪类,两种状态都会触发下划线动画,完美适配移动端交互逻辑。
内容的提问来源于stack exchange,提问作者vivelavie
相关产品推荐
相关产品推荐

