自定义window的原始函数。

这个问题的提出是因为最近有一个项目,设计部门把alert()的界面进行了设计,要求使用此设计进行开发。我以前真不知道alert()这种东西还能自定义,这不是原生的吗?原生的还能变?但是随着学习的深入,我发现是可以的,下边是我的思路:

首先我们知道所有的全局变量都是window对象的属性,所有的全局函数都是window对象的方法,alert()的执行可以这么干:window.alert();对于window对象来说,alert就是alert()函数的引用,我们重新给alert设置一个自定义函数的引用不就可以了吗?

代码如下:

<script>
window.alert=function () {
    console.log("自定义的alert");
}
alert();
</script>

执行之后控制台果然输出了“自定义的alert“,由此我们就可以控制alert()方法了,不就实现了想要的结果了吗?后续的,自己开始编码吧。下边是一个例子:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,initial-scale=1" />

<title>自定义alert()</title>
<style type="text/css">
body {}
</style>
</head>
<body>
<h1>自定义alert()</h1>

<div id="newAlert_Div" style='position:fixed;top:0px;left:0px;100%;height:100%;background:#000;opacity:0.4;display:none'>
    <div style='position:fixed;200px;height:90px;left:0px;right:0px;top:0px;margin:auto;bottom:0;display:block;font-size:1rem;background:yellow;text-align:center'><span id="newAlert_msg" style='position:relative;padding:15px;display:block'>这里是内容</span>
    <input type="button" value="确定" id="newAlert_button"></input>
    </div>
</div>
<script>
alert("原始消息框");
var newAlertButton = document.getElementById("newAlert_button");
var newAlertDiv = document.getElementById("newAlert_Div");
var newAlertMsg = document.getElementById("newAlert_msg");
window.alert = function(msg) {
    newAlertMsg.innerHTML = msg;
    newAlert_Div.style.display="block";
    newAlertButton.focus();
};
newAlertButton.addEventListener("click",function(){
    newAlert_Div.style.display="none";
},false);
alert("自定义消息框");
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/jingubang/p/4627068.html