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

Font Awesome SVG+JS实现按钮hover右侧箭头图标异常问题求助

解决Font Awesome箭头按钮悬停位置异常的问题

嘿,我来帮你搞定这个按钮箭头的小bug!先拆解下问题根源:你在按钮上直接加了fa-arrow-right类,Font Awesome的JS会自动把这个类转换成内置的SVG图标,这就是箭头默认出现在按钮左侧的原因。而你自己写的:before伪元素,一方面因为父按钮没设置定位参考导致位置跑偏,另一方面Font Awesome的自动渲染也干扰了伪元素显示,才出现了悬停时的空白方块。

下面是修改后的完整代码,我标注了关键修改点:

1. HTML部分

<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/all.js" integrity="sha384-xymdQtn1n3lH2wcu0qhcdaOpQwyoarkgLVxC/wZ5q7h9gHtxICrpcaSUfygqZGOe" crossorigin="anonymous"></script>
<div class="container mw-100 mx-auto margin-top-70 purple-background">
  <div class="row">
    <div class="col-8" id="forum">
      <h2 class="text-center margin-top-40">Join the Book Club</h2>
      <p class="feature-text">What are you reading? Share the book love over on the forum</p>
    </div>
    <div class="col-4">
      <div class="margin-top-60">
        <!-- 移除fa-arrow-right类,避免Font Awesome自动生成SVG干扰 -->
        <button class="btn btn-4 btn-4a">Join Us</button>
      </div>
    </div>
  </div>
</div>

2. CSS部分

/* 保留Font Awesome字体定义,确保伪元素能正确渲染箭头 */
.fa-arrow-right:before {
  font-family: 'Font Awesome 5 Solid';
  content: "\f061";
  font-weight: 900;
}

.btn-4 {
  border-radius: 50px;
  border: 3px solid #fff;
  color: #fff;
  overflow: hidden;
  /* 关键:给按钮设置相对定位,作为伪元素的定位参考 */
  position: relative;
  /* 给右侧箭头预留空间,避免文本和箭头重叠 */
  padding-right: 2.5em;
}

.btn-4:active {
  border-color: #17954c;
  color: #17954c;
}

.btn-4:hover {
  background: #24b662;
}

.btn-4:before {
  position: absolute;
  height: 100%;
  font-size: 125%;
  color: #fff;
  transition: all 0.3s;
  /* 用transform实现垂直居中,比line-height更可靠 */
  top: 50%;
  transform: translateY(-50%);
}

.btn-4:active:before {
  color: #17954c;
}

/* Button 4a - 调整箭头滑入逻辑 */
.btn-4a:before {
  /* 初始状态:箭头在按钮右侧外部 */
  left: 100%;
  /* 直接绑定箭头内容,确保字体生效 */
  content: "\f061";
  font-family: 'Font Awesome 5 Solid';
  font-weight: 900;
}

.btn-4a:hover:before {
  /* 悬停时:箭头滑到文本右侧,留出一点间距 */
  left: calc(100% - 1.5em);
}

3. JS部分(无需修改)

window.FontAwesomeConfig = { searchPseudoElements: true }

关键修改说明:

  • 移除按钮上的fa-arrow-right类:彻底避免Font Awesome自动生成的SVG图标干扰自定义伪元素。
  • 给.btn-4添加position: relative:让绝对定位的伪元素以按钮为参考,不会乱跑。
  • 替换line-height为transform: translateY(-50%):确保箭头在按钮内垂直居中,适配不同按钮高度。
  • 调整伪元素的初始和悬停位置:让箭头从按钮右侧外部滑入到文本右侧的预留空间里,不会覆盖文字。

这样修改后,常态下按钮右侧没有空白,悬停时箭头会平滑从右侧滑入到文本旁边,完美实现你想要的效果~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:02:44