首页 > 解决方案 > jQuery .fadeOut 方法和在 DOM 加载后附加的元素

问题描述

(我进入新兵训练营已经 9 周了,所以我为这潜在的基本性质道歉......)

我在条件内将一个元素附加到 DOM(一个按钮):

$('.buttonsAndInputs').append(`<button id="clearHistoryButton">Clear All</button>`);

单击此按钮时,它会运行一系列函数来清空数组并从 DOM 中清除一些其他内容。我想使用 jQuery 的 .fadeOut 方法来删​​除按钮。

我在后续函数中有这个:

$('#clearHistoryButton').remove();

我想:

$('#clearHistoryButton').fadeOut(1000);

......所以它以一种花哨的方式消失了。

它不起作用 - 它只是等待一秒钟然后 - POOF - 消失了。

这是我的第一个问题。这个社区对我在这个领域的成长至关重要,而且一如既往,我非常感谢你们所有人。

标签: javascriptjqueryanimationfadeouteffects

解决方案


你试过transition: opacity 1s你的CSS吗?

优点:
硬件加速 (GPU),即它不会打扰您的主处理器 (CPU) 执行此任务,而 jQuery 的fadeOut()功能是基于软件的,并且确实需要 CPU 资源来实现该效果。

脚步:

  1. 在此处添加 transition: opacity 1s所需按钮元素的 CSS 规则
    :( #clearHistoryButton)
  2. 使用button.fadeMeOutwith添加 CSS 规则opacity: 0
  3. 添加一个简单的 jQuery 函数以在单击时添加类“.fadeMeOut”
  4. 然后删除按钮setTimeout(function(){$('#clearHistoryButton').remove()},1000)

运行代码片段

$(function() { // Shorthand for $( document ).ready()

  $("#clearHistoryButton").on( "click", function() {
    // first: fade out the button with CSS
    $(this).addClass("fadeMeOut");

   // then: after fadeOut effect is complete, remove button from your DOM
    setTimeout(function(){
      $('#clearHistoryButton').remove();
    },1000);
  });
  
});
button {
  opacity: 1;
  -webkit-transition: opacity 1s;
  -moz-transition: opacity 1s;
  transition: opacity 1s;
}

button.fadeMeOut {
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="clearHistoryButton">Press to hide me</button>


推荐阅读