在用户离开页面之前显示模态表单

mač*_*ček 8 javascript jquery jquery-ui

我曾经习惯window.onbeforeunload在用户试图离开网站时显示自定义消息.

例:

window.onbeforeunload = function(){
  if(some_condition){
    return "Are you sure you want to navigate away from this page?\nAll unsaved changes will be lost.";
  }
};


+--------------------------------------------------------+
| Are you sure you want to navigate away from this page? |
| All unsaved changes will be lost.                      |
|                                                        |
|          [ Yes ]  [ Cancel ]                           |
+--------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

但是,我想稍微提高一点.如果可能的话,我想使用自定义模式表单而不是通用弹出窗口.

有没有办法做到这一点?

Man*_*jua 7

绑定到HTML对我来说非常有效,而不是卸载.这个原因在另一个答案中得到了很好的解释.

$("html").bind("mouseleave", function () {
    $('#emailSignupModal').modal(); \\or any modal
    $("html").unbind("mouseleave");
});
Run Code Online (Sandbox Code Playgroud)

如果您想在一天中或仅在任何其他特定条件匹配时显示模态,那么您可以使用cookie.

  • 这是一个糟糕的解决方案,因为每次用户将鼠标移到文档之外时都会触发此事件(在 Chrome 中)。 (2认同)

Joh*_*ler 6

卸载当用户尝试导航离开事件将触发.但是,如果您使用DIV作为弹出窗口,浏览器将在用户有机会阅读之前离开.

要将它们保留在那里,您必须使用警报/提示/确认对话框.(我所知道的)