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

CSS与JavaScript滚动按钮动画不一致问题求助

CSS与JavaScript滚动按钮动画不一致问题求助

我想做一个滚动按钮效果:鼠标悬停时文字部分滑出来,离开时滑回去,但这个动画的表现特别不稳定。

这段代码第一次执行是正常的,但后续循环就全乱了——有时候我还在悬停,no_length类就莫名被加上了;鼠标离开时,元素的classList里居然同时有no_length和full_length;偶尔消失动画根本没做完,按钮条就直接消失了;还有时候悬停触发会有延迟。

我试过在悬停时先移除所有相关类再重新添加,也试过加is_transitioning状态来防止重复触发,但这些方法都不管用,实在找不到问题出在哪了。

我的代码:

JavaScript

var is_transitioning = false;

$(".btn").hover(appear, dissappear);


function appear() {
  if (!is_transitioning) {
    is_transitioning = true;
    $(".button").removeClass("no_length");
    $(".button").removeClass("full_length");
    $(".button").removeClass("del_btn");
    $(".button").addClass("move_btn");

    setTimeout(function() {
      $(".button").addClass("full_length");
      $(".button").removeClass("move_btn");

    }, 2000);
  }
}

function dissappear() {
  $(".button").removeClass("full_length");
  $(".button").addClass("del_btn");
  setTimeout(function() {
    $(".button").addClass("no_length");
    $(".button").removeClass("del_btn");
    is_transitioning = false; // Reset transition state after the transition
  }, 2000); // Time for disappear transition
}

CSS

.btn {
  display: flex;
  align-items: center;
  width: 150px;
}

.btn:hover {
  cursor: pointer;
  .button {
    background-color: #3f51b5;
  }
  .button_circle {
    border-color: #3f51b5;
  }
}

.button {
  background-color: #4f7b8a;
  border-radius: 20px;
  width: 0;
  color: #E5E4E2;
  position: relative;
  transform: translateX(-40px);
  z-index: 0;
  height: 25px;
  padding-left: 30px;
  font-size: 15px;
  text-align: center;
}

.full_length {
  width: 100px!important;
}

.no_length {
  width: 0px!important;
}

.button_circle {
  height: 40px;
  width: 40px;
  background-color: #bbb;
  border-radius: 50%;
  box-sizing: border-box;
  border: 2px solid #4f7b8a;
  display: inline-block;
  z-index: 1;
}

.move_btn {
  animation: appear 2s 0s 1 ease;
}

.del_btn {
  animation: dissapear 2s forwards;
}

@keyframes appear {
  0% {
    width: 0;
  }
  100% {
    width: 100px;
  }
}

@keyframes dissapear {
  0% {
    width: 100px;
  }
  100% {
    width: 0;
  }
}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="btn">
  <span class="button_circle"></span>
  <button class="button" type="submit">SEND MESSAGE</button>
</div>

备注:内容来源于stack exchange,提问作者黃柏瑋

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 09:24:52