检查元素是否正在淡出(Javascript / Jquery)

4

有没有一种方法可以检查一个元素是否正在淡出?

类似于这样的代码(伪代码):

while(element.isFadingOut()){
//do something
}

我需要的是 isFadingOut(),它是否存在?

请注意,在Javascript中无法在循环中检查异步完成,因为淡入淡出效果跨越多个浏览器周期。 - iCollect.it Ltd
2个回答

4
如果您只想检查某个东西是否正在淡化,只需检查opacity值是否小于1.0即可: JSFiddle:http://jsfiddle.net/TrueBlueAussie/vkcpknLh/ 以下是jQuery扩展代码:
$.fn.isFading = function(){
    return this.css('opacity') < 1;
};

注意:淡出是一种异步操作,因此在循环中检查将永远无法工作。您需要通过定时器等方式进行轮询(如我的JSFiddle所示)。

另一种选择是使用fadeOut的完成事件:

 element.fadeOut(function() {
       // do something on completion
 });

或者使用jQuery动画提供的 promise 功能:

 element.fadeOut().promise().done(function(){
       // do something on completion of all animations for this element
 });

更新:

注意: 如果元素已经处于最终状态,则某些动画事件不会触发 done。此时应在 promise 上使用 always():

 element.fadeOut().promise().always(function(){
       // do something on completion of all animations for this element
 });

0

当您实际淡出时,可以添加触发器,例如:

$(element).fadeOut("normal", function () {
// your other code
$(this).trigger('isFadingOut');
});  

并在其他地方监听此事件

$(element).on('myFadeOutEvent',function() {
// do something
});

使用您所使用的元素进行替换。注意:如果您使用JQuery,则这将起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接