自定义模拟iphone弹窗,替换原生alert

1,193 阅读1分钟

1.为什么要更改原生alert?

很多app打开h5都会把alert给禁止掉,因为alert会阻塞js,例如百度app就禁止alert弹出。话不多说,直接上代码。

window.alert = function (text) {
            var div = document.createElement('div');
            div.id = 'alert';
            div.innerHTML = "<div style=\"width: 280px;position: fixed;top: 50%;left: 50%;z-index: 999;background: #fff;margin-left: -140px;margin-top: -100px;border-radius: 10px;text-align: center;box-shadow: 0 0 10px #999;\"><h4 style=\"margin: 16px 0;padding: 0 16px;\">" + text + "</h4><div onclick=\"document.getElementById('alert').remove()\" style=\"border-top: solid 1px #ccc;line-height: 40px;color: #2196F3;\">确定</div></div><style>#alert{width: 100%; height: 100%;position: fixed;top:0;z-index: 999}</style>";
            document.getElementsByTagName('body')[0].appendChild(div);
        }

效果预览

1639393828685.jpg