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/