移动端alert()重构

418 阅读1分钟

alert和confirm去掉网址。网上大多的回答。实现了去掉网址,但是网址那块显示了about:blank。

    let iframe = document.createElement("IFRAME");    iframe.style.display="none";    iframe.setAttribute("src", 'data:text/plain,');    document.documentElement.appendChild(iframe);    window.frames[0].window.alert(msg);    iframe.parentNode.removeChild(iframe);

参考了juejin.cn/post/684490…

/* 参数说明
 * @title => String, 标题, 非必填, 默认值为"提示"
 * @msg => String, 内容, 非必填, 默认值无
 * @type => Number, 类型,0为alert提示框,非0为confirm提示框, 非必填, 默认值0
 * @callbak => Function, 点击按钮回调,confirm方法有回调参数,取消返回false,确认返回true, 非必填, 默认值无
 */
function openAlert(title, msg, type, callback) {
    var v = document.createElement("div");
    var s = document.createElement("div");
    s.style.cssText = "width:100%;height:100%;position:absolute;top:0;left:0;background:rgba(0,0,0,0.5);";
    v.appendChild(s);
    var b = document.createElement("div");
    b.style.cssText = "width:80%;position:absolute;top:50%;left:50%;background:#fff;border-radius:4px;overflow:hidden;transform:translate(-50%,-50%);-webkit-transform: translate(-50%,-50%);";
    title = title || '提示';
    var t = document.createElement("div");
    t.style.cssText = "font-size:16px;text-align:center;line-height:20px;padding:20px 10px 10px;color:#333;font-weight:bold;";
    t.innerHTML = title;
    b.appendChild(t);

    msg = msg || '';
    if (msg) {
      var m = document.createElement("div");
      m.style.cssText = "font-size:16px;text-align:center;padding:10px;color:#888;";
      m.innerHTML = msg;
      b.appendChild(m);
    }
    v.appendChild(b);

    type = type || 0;
    var f = document.createElement("div");
    f.style.cssText = "border-top:1px solid #eee;display:-webkit-flex;display:flex;margin-top:10px;";
    if (type != 0) {
      var b1 = document.createElement("div");
      b1.style.cssText = "-webkit-flex:1;flex:1;font-size:16px;text-align:center;padding:15px;color:#888;font-weight:bold;border-right:1px solid #eee;";
      b1.innerHTML = "取消";
      f.appendChild(b1);
      b1.onclick = function() {
          typeof callback == 'function' && callback(false);
          document.body.removeChild(v);
      };
    }
    var b2 = document.createElement("div");
    b2.style.cssText = "-webkit-flex:1;flex:1;font-size:16px;text-align:center;padding:15px;color:#556993;font-weight:bold;";
    b2.innerHTML = "确认";
    b2.onclick = function() {
        typeof callback == 'function' && callback(true);
        document.body.removeChild(v);
    };
    f.appendChild(b2);

    b.appendChild(f);
    document.body.appendChild(v);
}


window.alert = function(msg, callback) {
    openAlert('提示', msg, 0, function() {
        typeof callback == 'function' && callback();
    });
};

window.confirm = function(msg, callback) {
    openAlert('提示', msg, 1, function(boo) {
        typeof callback == 'function' && callback(boo);
    });
};