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

如何实现按钮点击时底部边框呈现:hover缩放效果?已尝试:focus无效

问题:点击按钮时底部边框缩小至hover状态,使用:focus伪类无效

我想要实现点击按钮时,底部边框缩小到和:hover状态一样的样式,尝试用:focus伪类实现但没效果,请求技术帮助。

相关代码

CSS代码

.hb-border-bottom-br4 {
  position: relative;
  overflow: visible;
  box-sizing: border-box;
  padding: 10px 22px;
}

.hb-border-bottom-br4::after {
  display: block;
  content: '';
  border-bottom-width: 2px;
  border-color: #438C7B;
  transform: scaleX(1);
  transition: transform 300ms ease-in-out;
}

.hb-border-bottom-br4:hover::after {
  transform: scaleX(0.5);
}

HTML代码

<div class="grid grid-cols-2 gap-4 text-md lg:text-lg text-white mt-10 ">
  <div class="col-span-1">
    <button class="hbtn hb-border-bottom-br4 p-2 w-full mb-5 outline-none" on:click={()=> video = 'video1'}>
                        Como usar a plataforma
                    </button>
  </div>
  <div class="col-span-1">
    <button class="hbtn hb-border-bottom-br4 p-2 w-full mb-5 outline-none" on:click={()=> video = 'video2'}>
                        Como adquirir a licença
                        <br>
                    </button>
  </div>
</div>

解决方案

1. 修复基础样式(先让边框正常显示)

原CSS中::after伪元素缺少两个关键属性,导致边框根本无法显示:

  • border-style: solid:没有指定边框样式,仅设置宽度和颜色不会渲染出边框
  • width: 100%:块级伪元素内容为空时默认宽度为0,需设置宽度匹配按钮宽度
  • 可选添加transform-origin: center:确保缩放从边框中心开始,和hover效果逻辑一致

修改后的基础伪元素样式:

.hb-border-bottom-br4::after {
  display: block;
  content: '';
  width: 100%;
  border-bottom: 2px solid #438C7B; /* 合并写法,同时设置宽度、样式、颜色 */
  transform-origin: center;
  transform: scaleX(1);
  transition: transform 300ms ease-in-out;
}

2. 添加点击/聚焦状态的样式

如果需要点击按钮时(按下瞬间)或按钮获得焦点时触发缩小效果,直接给:focus和:active伪类添加对应样式:

.hb-border-bottom-br4:hover::after,
.hb-border-bottom-br4:focus::after,
.hb-border-bottom-br4:active::after {
  transform: scaleX(0.5);
}

3. 点击后保持效果(可选)

如果希望点击按钮后持续保持缩小的边框(即使点击其他元素也不恢复),需要结合JavaScript添加自定义类:

  • 修改按钮的点击事件,切换active类:
<button class="hbtn hb-border-bottom-br4 p-2 w-full mb-5 outline-none" on:click={()=> { video = 'video1'; this.classList.toggle('active'); }}>
  Como usar a plataforma
</button>
  • 添加对应CSS样式:
.hb-border-bottom-br4.active::after {
  transform: scaleX(0.5);
}

内容的提问来源于stack exchange,提问作者Iago Alexandre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:51:32