自定义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;width:100%;height:100%;background:#000;opacity:0.4;display:none'>
    <div style='position:fixed;width: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值