jquery - 使用when和done和settimeout显示隐藏div

标签 jquery settimeout show-hide

function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  $.when(
    setTimeout(function() {
      closecustomBox();
    }, 3000)
  ).done(function(x) {
    $('#anotherdialog').show();
  });
})
#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dialog"></div>

<div id="anotherdialog"></div>


<div id="show">show</div>

我想要发生的是点击显示后将显示红色框,3秒后红色框将隐藏,然后蓝色框应显示。

I want to achieve here is to not make the 2 div appear together

最佳答案

如果您想使用 $.when 那么您需要传入 $.Deferred() 作为参数。然后在超时完成后解析 $.Deferred() ,这将调用我们之前传递给 .done() 的方法。

我还通过 CSS 将对话框的初始状态设置为 display: none; 以避免最初通过 JS 隐藏它们。

我还提供了一个不使用 jQuery deferred 的替代方案,它也达到了相同的结果。

function closecustomBox() {
  $('#dialog').hide();
}

var dialog = $('#dialog');
var anotherDialog = $('#anotherdialog');
var timeout;

$("#show").click(function() {
  dialog.show();
  anotherDialog.hide();

  def = $.Deferred();
  $.when(def).done(function() {
    closecustomBox();
    anotherDialog.show();
  });

  if (timeout) clearTimeout(timeout); // Clear out any old timeouts to avoid flickers and strange behavior
  timeout = setTimeout(function() {
    def.resolve(); // Resolve the Deferred which will call def.done's callback
  }, 3000);
})

// Or if you don't want to use promises you can just elminate them entirely and simplify this example greatly
var timeout2;
 $("#show-2").click(function() {
      dialog.show();
      anotherDialog.hide();

      if (timeout) clearTimeout(timeout); // Clear out any old timeouts to avoid flickers and strange behavior
      timeout = setTimeout(function() {
        closecustomBox();
        anotherDialog.show();
      }, 3000);
    })
#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
  display: none;
}

#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dialog"></div>

<div id="anotherdialog"></div>


<div id="show">show</div>

<div id="show-2">Alternate Show</div>

关于jquery - 使用when和done和settimeout显示隐藏div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44363341/

相关文章:

javascript - Jquery 文件树 - 如何在文件夹单击时返回文件夹名称

javascript - 钢琴应用程序的具有动态持续时间的 setTimeout 函数

android - 每 5 秒隐藏一次可见按钮

jQuery 隐藏和显示第 n 个元素后的 div 列表

jquery - Bootstrap - 如何使用选择中的选项显示模式框?

jquery - 我正在使用的 jQuery 电子邮件混淆脚本存在问题

php - 具有高级(列)过滤的 CRUD?

JavaScript 递归延迟方法调用

javascript - 即使使用 setTimeout 和 promises 函数仍然执行

jquery - 如何使 bootstrap-multiselect 不可见我的默认值?