• 自定义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>
  • 相关阅读:
    Uber Go 语言编码规范
    前端架构演进
    看完微软大神写的求平均值代码,我意识到自己还是too young了 https://mp.weixin.qq.com/s/r2nOJvviqK2bZAumNkc7g
    React v18.0 How to Upgrade to React 18
    重写历史 Rewriting History
    记一次网页内存溢出分析及解决实践
    降低了IP层的效率 根据对方给出的窗口值和当前网络的拥塞的程度决定一个报文段应包含多少个字节
    京东家庭号前端分层架构演进及赋能实践
    深入了解 Go 语言与并发编程 GMP
    BBR原理导读
  • 原文地址:https://www.cnblogs.com/jingubang/p/4627068.html
Copyright © 2020-2023  润新知