简体   繁体   English

自定义JavaScript警报不会阻止页面关闭

[英]Custom JavaScript alert not stopping page from closing

I'm using the custom alert below when page is about to close. 页面即将关闭时,我正在使用以下自定义警报。 The issue is that the alert pups up and the page closes before the user can click the OK button on the custom alert. 问题在于,在用户可以单击自定义警报上的“确定”按钮之前,警报会弹出并关闭页面。 What is missing is the custom alert that it cannot keep the page open till the user clicks the OK button? 缺少的自定义警报是自定义警报,直到用户单击“确定”按钮,它才能保持页面打开状态?

window.onbeforeunload = function() {
   {
      return custom_alert(head, txt);
   }


function custom_alert(head, txt) {
  var d = document;
  var c_obj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
  c_obj.id = "contain";
  c_obj.style.height = d.documentElement.scrollHeight + "px";
  var alertObj = c_obj.appendChild(d.createElement("div"));
  alertObj.id = "alert";
  if (d.all && !window.opera)
    alertObj.style.top = document.documentElement.scrollTop + "px";
  alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
  alertObj.style.visiblity = "visible";
  var h1 = alertObj.appendChild(d.createElement("h1"));
  h1.appendChild(d.createTextNode(head));
  var msg = alertObj.appendChild(d.createElement("p"));
  msg.innerHTML = txt;
  var btn = alertObj.appendChild(d.createElement("a"));
  btn.id = "close";
  btn.appendChild(d.createTextNode('ok'));
  btn.focus();
  btn.onclick = function() {
    c_obj.parentNode.removeChild(c_obj);
  };
  alertObj.style.display = "block";
}

I found a library that solves this problem: 我找到了一个解决此问题的库:

http://t4t5.github.io/sweetalert/ http://t4t5.github.io/sweetalert/

The offical alert: alert("Oops... Something went wrong!"); 官方警报: alert("Oops... Something went wrong!");

The changed alert: sweetAlert("Oops...", "Something went wrong!", "error"); 更改后的警报: sweetAlert("Oops...", "Something went wrong!", "error");

This library solves many of the problems of creating your own alert. 该库解决了创建您自己的警报的许多问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM