javascript - jQuery .fadeOut 方法和在 DOM 加载后附加的元素
问题描述
(我进入新兵训练营已经 9 周了,所以我为这潜在的基本性质道歉......)
我在条件内将一个元素附加到 DOM(一个按钮):
$('.buttonsAndInputs').append(`<button id="clearHistoryButton">Clear All</button>`);
单击此按钮时,它会运行一系列函数来清空数组并从 DOM 中清除一些其他内容。我想使用 jQuery 的 .fadeOut 方法来删除按钮。
我在后续函数中有这个:
$('#clearHistoryButton').remove();
我想:
$('#clearHistoryButton').fadeOut(1000);
......所以它以一种花哨的方式消失了。
它不起作用 - 它只是等待一秒钟然后 - POOF - 消失了。
这是我的第一个问题。这个社区对我在这个领域的成长至关重要,而且一如既往,我非常感谢你们所有人。
解决方案
你试过transition: opacity 1s
你的CSS吗?
优点:
硬件加速 (GPU),即它不会打扰您的主处理器 (CPU) 执行此任务,而 jQuery 的fadeOut()
功能是基于软件的,并且确实需要 CPU 资源来实现该效果。
脚步:
- 在此处添加
transition: opacity 1s
所需按钮元素的 CSS 规则
:(#clearHistoryButton
) - 使用
button.fadeMeOut
with添加 CSS 规则opacity: 0
- 添加一个简单的 jQuery 函数以在单击时添加类“.fadeMeOut”
- 然后删除按钮
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>
推荐阅读
- c - 无论我输入哪一年,我的程序总是告诉我它是闰年,即使它不是
- go - 如何在gorm中使多个模型自动迁移
- rust - 与 Rc 匹配
> - java - 如何在 Spring Boot 中调试请求?
- java - 以下哪种方法会导致 s 引用的字符串对象发生变化?
- ios - iOS - 是否有以编程方式创建多个不分割屏幕的窗口?
- xamarin - 从 iOS 获取 Shell TabBar 高度
- c# - 如何提交包含现有选择的多个复选框选择并将新修改的项目保存在 ASP.NET MVC 中
- java - 当 Java 更新到 OpenJDK 11 时,Windows 上的 Jenkins 返回不受支持的 JVM 错误
- javascript - 客户端,如何信任来自物联网设备的自签名证书?