在 jQuery 中,淡出效果(fadeOut)是一种动画效果,它会将元素的透明度从 100%(完全不透明)逐渐降低到 0%(完全透明),最终将元素的 display
属性设置为 none
。但淡出后元素仍然存在于 DOM 中,只是不可见。
要在淡出效果完成后删除 DOM 元素,可以使用 jQuery 的 fadeOut()
方法的回调函数,或者在淡出效果完成后使用 remove()
方法。
$(selector).fadeOut(duration, function() {
$(this).remove();
});
$(selector).fadeOut(duration).promise().done(function() {
$(this).remove();
});
<!DOCTYPE html>
<html>
<head>
<title>淡出后删除元素示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #3498db;
margin: 10px;
}
</style>
</head>
<body>
<div class="box" id="box1">Box 1</div>
<div class="box" id="box2">Box 2</div>
<button id="fadeAndRemove">淡出并删除</button>
<script>
$(document).ready(function() {
$('#fadeAndRemove').click(function() {
// 淡出第一个盒子并在完成后删除
$('#box1').fadeOut(1000, function() {
$(this).remove();
console.log('Box 1 已被删除');
});
// 另一种写法
$('#box2').fadeOut(1000).promise().done(function() {
$(this).remove();
console.log('Box 2 已被删除');
});
});
});
</script>
</body>
</html>
duration
:可选参数,指定动画持续的时间,可以是毫秒数或字符串 "slow"
(600 毫秒)、"fast"
(200 毫秒)callback
:可选参数,动画完成后执行的回调函数$(document).ready()
或简写 $(function() {})
)fadeOut()
前添加代码这种技术常用于:
没有搜到相关的文章