javascript - jQuery - 设置和重置转换延迟

标签 javascript jquery html css settimeout

  • 我通过添加事件类来触发过渡动画。

  • 在动画结束时,我删除了事件类(在 延迟),以便再次触发。

这在第一次迭代时效果很好,但后续迭代和单击 close 函数不会重置延迟计数。

超时计时器显然需要在每次点击时清除或重置,但我无法让它始终如一地工作。我一直在尝试使用 clearTimeout() 函数。

$("#btn").on('click', function() {
  $("#msg").prop("class", "alert active");
  removeActive();
});

function removeActive() {
  $("#msg").on("transitionend", function() {
    setTimeout(function() {
      $("#msg").removeClass("active");
    }, 3000)
  });
}

$("#close").on("click", function() {
  $("#msg").removeClass("active");
});
.alert {
  position: fixed;
  right: 20px;
  bottom: -100px;
  display: flex;
  padding: 10px;
  width: auto;
  max-width: calc(100% - 40px);
  background: #3dc0f1;
  color: #fff;
  transition: all ease-in-out 0.3s;
  z-index: 10;
}

.alert.active {
  bottom: 20px;
}

#msg-tx {
  padding: 10px 20px 10px 10px;
}

#close {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 5px;
  transition: all ease-in-out 0.3s;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="submit">Go</button>

<div id="msg" class="alert">
  <p id="msg-tx">Hello There</p>
  <div id="close">X</div>
</div>

多次单击 Go 按钮,导致超时变得不一致。

最佳答案

通过动画化另一个属性(在本例中为翻译)来依赖 CSS 延迟,并使 jQuery 代码更容易。

$("#btn").on('click', function() {
  $("#msg").removeClass("active");
  setTimeout(function() {      
    $("#msg").addClass("active");
   }, 200)
});

$("#close").on("click", function() {
  $("#msg").removeClass("active");
});
.alert {
  position: fixed;
  right: 20px;
  bottom: -100px;
  display: flex;
  padding: 10px;
  width: auto;
  max-width: calc(100% - 40px);
  background: #3dc0f1;
  color: #fff;
  transition: all ease-in-out 0.2s;
  z-index: 10;
}

.alert.active {
  bottom: 20px;
  transform:translateY(calc(100% + 40px));
  transition: bottom ease-in-out 0.3s,transform 0.3s 3s;
}

#msg-tx {
  padding: 10px 20px 10px 10px;
}

#close {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 5px;
  transition: all ease-in-out 0.3s;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="submit">Go</button>

<div id="msg" class="alert">
  <p id="msg-tx">Hello There</p>
  <div id="close">X</div>
</div>

关于javascript - jQuery - 设置和重置转换延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57921083/

相关文章:

php - 将 NULL 显示为无文本

Javascript/jQuery .load 将多个文件加载到 div 中

javascript - 可拖动和可排序的 Jquery 看起来不太好

javascript - 拆分内容段落,光标在哪里 - Javascript

javascript - Safari 中的 html2canvas 不在 SVG 路径上呈现 Javascript style.fill

jquery - 在 Iframe 内容完全加载到 colorbox 之前,加载 gif 图像会停止

jquery - 使用 jquery 的 asp.net mvc RC 中的模态表单

javascript - 使用 jQuery .append 时,子级的父级不会得到更新

javascript - 如何遍历所有 <p> 元素?

顶部的 HTML 静态栏覆盖了该部分的链接