简体   繁体   English

使用 jquery 在 n 秒后阻止“显示然后隐藏”

[英]Blocking 'show then hide' after n seconds with jquery

I am trying to perform something pretty easy at first glance but I can not do it.乍一看,我正在尝试执行一些很容易的事情,但我做不到。 I have a button, and two hidden div.我有一个按钮和两个隐藏的 div。 When the button is pushed, I want the first div to show and after n seconds, to hide and then the second div show.按下按钮时,我希望显示第一个 div,并在 n 秒后隐藏,然后显示第二个 div。

html: html:

<button id="button">
  push
</button>
<div id="div1" style="display:none">
  firstDiv
</div>
<div id="div2" style="display:none">
  secondDiv
</div>

The whole code, with the JS is here: https://jsfiddle.net/439xbfe5/带有JS的整个代码在这里: https://jsfiddle.net/439xbfe5/

I have already checked the answers here: jQuery show for 5 seconds then hide我已经在这里检查了答案: jQuery show for 5 seconds then hide

The problem for this code is #div2 shows up before #div1 disapears:此代码的问题是 #div2 在 #div1 消失之前出现:

$("#button").click(()=>{

  var timeLimit = 5000;
  $("#div1").show().delay(timeLimit).fadeOut();
  $("#div2").show();
  
});

Same problem here:这里同样的问题:

$("#button").click(()=>{

  var timeLimit = 5000;
  $("#div1").show();
  setTimeout(function() { $("#div1").hide(); }, timeLimit );
  $("#div2").show();
  
});

I also tried to create a blocking sleep function like:我还尝试创建一个阻塞睡眠 function ,例如:

function sleep(ms){
  var start = new Date().getTime();
  while(true){ 
    if(new Date().getTime()-start>ms){
        return; 
     }
  }
}

$("#button").click(()=>{

  var timeLimit = 5000;
  $("#div1").show();
  sleep(timeLimit);
  $("#div2").show();
});

But this doesnt work at all.但这根本不起作用。

Also, showing #div2 is just an illustration of my problem.此外,显示#div2 只是我的问题的一个说明。 Actually, I dont need to 'compilate' show then hide but #div1 is more like a transition step between before and after the button is pushed.实际上,我不需要“编译”显示然后隐藏,但#div1 更像是按下按钮之前和之后之间的过渡步骤。 I hope you understood my problem (sorry for my english).我希望你理解我的问题(对不起我的英语)。

Thx !谢谢 !

You have to use the complete callback function to do something "after" a jquery animation is done.您必须使用complete的回调function 在 jquery animation 完成“之后”执行某些操作。

 $("#button").click(()=>{ var timeLimit = 5000; $("#div1").show().delay(timeLimit).fadeOut(function(){ $("#div2").show(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="button"> push </button> <div id="div1" style="display:none"> firstDiv </div> <div id="div2" style="display:none"> secondDiv </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM