首页 > 解决方案 > 在弹出确认对话框之前做一些事情

问题描述

$('.lorem').on('click', function(){
    $(this).hide();
    if(prompt('DO SOMETHING') != null) {console.log('something');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='lorem'>lorem</div>

所以我首先想隐藏 div 然后弹出确认对话框。可能吗?

标签: javascriptjqueryconfirm

解决方案


在下一次绘制之前使用动画帧运行代码。

window.requestAnimationFrame()

$('.lorem').on('click', function(){
    // The browser will paint async not sync, so the div may still be visible
    // even after this line
    $(this).hide();
    // when the browser is ready to paint the div off screen the callback will fire
    window.requestAnimationFrame(() => { 
        if (prompt('DO SOMETHING') != null) {
            console.log('something');
        }
    });
});

注意:您可能需要嵌套动画帧,因为浏览器倾向于以不同的方式实现请求动画帧。

requestAnimationFrame(() => requestAnimationFrame(() => {
    ...
})); 

推荐阅读