【问题标题】:do something before confirm dialog pops up在弹出确认对话框之前做一些事情
【发布时间】:2018-11-24 20:48:50
【问题描述】:

$('.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 然后弹出确认对话框。有可能吗?

【问题讨论】:

  • 是的,在动画帧中抛出提示window.requestAnimationFrame(() =&gt; {if(prompt('DO SOMETHING') != null) {console.log('something');} }
  • 您可能需要执行嵌套动画帧回调,因为它会在下一次重绘之前运行,例如:requestAnimationFrame(() =&gt; { /* div is about to be hidden on next paint*/ requestAniamtionFrame(() =&gt; { /* div was hidden on last paint */} })
  • @JayHarris,请不要告诉我我需要使用整个 API 来隐藏 div?
  • hide 接受一个回调函数,当动画完成时:api.jquery.com/hide/#hide-duration-complete -move your prompt there

标签: javascript jquery confirm


【解决方案1】:

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

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(() => {
    ...
})); 

【讨论】:

    【解决方案2】:

    您可以使用 setTimeout:

     document.querySelector('.lorem').addEventListener('click',  () => {
      document.querySelector('.lorem').style.display = "none";
       setTimeout(() => {
         if(prompt("do something") !== null) {
           console.log('do something')
         }
       }, 100)
      })
    

    【讨论】:

    • 请注意,settimeout 不保证在下一次重绘之前运行。理论上,JavaScript 可以在决定重绘之前运行多个任务。
    • 似乎 OP 正在根据他对您的回答的反应方式寻找一个简单的解决方案,所以我给了他一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多