我有一個 div id #scenario,它有許多<p>元素作為子元素。我想要一個函式,以相反的順序將它們一個一個地淡出,然后從 DOM 中洗掉它們。我正在使用 jQuery。
我的代碼:
function fadeAndDelete() {
var elements = $("#scenario").children().get().reverse();
$.each(
elements, function(index, element) {
element.animate(
{'color': 'rgba(0, 0, 0, 0)'}, 1000, function() {
$(this).remove();
}
);
}
)
};
我也嘗試使用element.remove()and $(element).remove(),但都沒有奏效。
加分項:在理想的世界中,洗掉元素之間會有時間間隔(就像在 each() 回圈之間使用 sleep() 函式一樣)。
uj5u.com熱心網友回復:
在animate()你使用的是DOM影片,沒有jQuery的:
https://developer.mozilla.org/en-US/docs/Web/API/Element/animate
animate(keyframes, options)
這個函式沒有回呼引數,所以.remove()不是不起作用,而是這個函式從來沒有被呼叫過。
要使用 jquery,animate您需要一個 jquery 物件:
$.each(elements, function(index, element) {
$(element).animate(...
但是,請注意,jquery 因在沒有附加插件或使用 css 的情況下無法影片顏色而臭名昭著,因此您的代碼將不會影片,但.remove()會被呼叫。
對于一次一個場景,您可以使用setTimeout. 對此,SO 上有很多現有答案,但這是您的代碼:
function fadeAndDelete() {
var elements = $("#scenario").children().get().reverse();
$.each(elements, function(index, element) {
setTimeout(function() {
$(element).fadeOut(2000, function() {
this.remove();
});
}, index*500);
});
};
fadeAndDelete();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=scenario>
<div>a</div>
<div>b</div>
<div>c</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/384259.html
標籤:javascript 查询 css动画 jquery-动画
上一篇:擴展攔截下載的問題
下一篇:我輸入后輸入失去焦點
