在jquery中设置延迟,以便在点击时立即淡出或淡出

时间:2010-05-20 13:22:25

标签: jquery notifications

我正在尝试修改脚本以获取通知弹出窗口。当用户点击消息时,我不希望弹出窗口在X秒或淡出后淡出。我可以让两个效果单独工作,但当我尝试将它们组合起来时,fadeOut可以正常工作。到目前为止,这是我的代码:

function notify(data, type) {
 switch(type) {
 case "success":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifySuccess')
  .click(function() {
$("#notify").fadeOut();
  })
  .delay(5000).fadeOut();
break;
 case "error":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifyFailure')
  .click(function() {
$("#notify").fadeOut();
  })
  .delay(5000).fadeOut();
break;
}
}

2 个答案:

答案 0 :(得分:1)

你需要.stop()来清除队列中的延迟,如下所示:

function notify(data, type) {
 switch(type) {
 case "success":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifySuccess')
  .click(function() {
    $("#notify").stop(true, true).fadeOut();
  })
  .delay(5000).fadeOut();
break;
 case "error":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifyFailure')
  .click(function() {
    $("#notify").stop(true, true).fadeOut();
  })
  .delay(5000).fadeOut();
break;
}
}

另外,如果您只有successerror类型,那么您可以将其缩短很多,例如:

function notify(data, type) {
 $('#notify').html(data)
   .removeAttr("style")
   .addClass(type == 'success' ? 'notifySuccess' : 'notifyFailure')
   .delay(5000).fadeOut()
   .click(function() {
     $(this).stop(true, true).fadeOut();
   });
 }

答案 1 :(得分:0)

尝试放入.stop();

.click(function() {
    $("#notify").stop(true,true).fadeOut(); // also in this part, you may change $("#notify") to $(this)
})