简体   繁体   English

为什么不淡出和淡入jquery?

[英]Why not fading out and fading in jquery?

I've been trying this for several hours 我已经尝试了几个小时

    $('#position-name').html('Successfuly Changed').fadeOut(1000);
    $('#position-name').html('New Name').fadeIn();

I know its simple but, I don't know the reason why If I run those line within my code only New Name that keep showing up despite the given effect. 我知道它很简单,但是,我不知道为什么如果在代码中运行这些行,那么只有给定效果的新名称仍会继续显示。

It fadeOut the New Name and then FadeIn the New Name again 它淡出新名称 ,然后再次淡入新名称

why Is it not fading out or showing successfully changed ? 为什么不褪色或显示成功更改

The problem is: Your code reads like -change the element html to 'Successfuly Changed' -then while fadOut() with 1000 its directly change to 'New Name' -so you can see it fadeOut() and then fadeIn() .. To avoid that you need to use fadeOut() callback function 问题是:您的代码读取为-将元素html 'Successfuly Changed''Successfuly Changed' -然后将fadOut()1000直接更改为'New Name'您可以看到它fadeOut()然后fadeIn() 。为了避免这种情况,您需要使用fadeOut()回调函数

 $('#position-name').html('Successfuly Changed').fadeOut(1000 ,function(){ $(this).html('New Name').fadeIn(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="position-name"></div> 

Both fadeOut and fadeIn are asynchronous functions. fadeOut和fadeIn都是异步函数。 Meaning, that once you call them, the action will happen in the background and your code immediately returns and continues onto the next statement. 这意味着,一旦调用它们,该操作将在后台发生,并且您的代码立即返回并继续执行下一条语句。

In your example, you start a fadeout over a second, but as soon as it starts you replace the content of the div and fade in. Because the fadeout has only run for a microsecond, jquery internally cancels the fadeOut action and runs a fadeIn which doesnt need to do anything. 在您的示例中,您需要花一秒钟的时间开始淡入淡出,但是一旦它开始,您就替换了div的内容并淡入。由于淡入仅运行了微秒,因此jquery在内部取消了fadeOut操作并运行了fadeIn不需要做任何事情。

Both these functions take a second parameter which is a 'complete' callback. 这两个函数都采用第二个参数,即“完整”回调。 You should structure your code as follows. 您应该按以下方式组织代码。

  $('#position-name').html('Successfuly Changed').fadeOut(1000, 
    function () {
      $('#position-name').html('New Name').fadeIn();
  });

 $( "#clickme" ).click(function() { var message = $('#position-name'); message.html('Successfuly Changed').fadeOut(1000, function() { message.html('New Name').fadeIn("slow"); }); }); 
 #box { width: 200px; height: 50px; outline: 2px solid; line-height: 50px; text-align: center; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> You can add the next animation in the callback funciton of fadeOut. After 1 second of the fadeout animation the new fadeIn will start. <div id="box"> <div id="position-name"></div> </div> <button id="clickme">CLICK ME</button> 

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

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