日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

js实现自定义弹窗

發(fā)布時(shí)間:2024/9/19 综合教程 43 生活家
生活随笔 收集整理的這篇文章主要介紹了 js实现自定义弹窗 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

  眾所周知,瀏覽器自帶的原生彈窗很不美觀,而且功能比較單一,絕大部分時(shí)候我們都會(huì)按照設(shè)計(jì)圖自定義彈窗或者直接使用注入layer的彈窗等等。前段時(shí)間在慕課網(wǎng)上看到了一個(gè)自定義彈窗的實(shí)現(xiàn),自己順便就學(xué)習(xí)嘗試寫了下,下面是主要的實(shí)現(xiàn)代碼并添加了比較詳細(xì)的注釋,分享出來供大家參考。(代碼用了ES6部分寫法如需兼容低版本瀏覽器請(qǐng)把相關(guān)代碼轉(zhuǎn)成es5寫法,后面有時(shí)間更新為一個(gè)兼容性較好的es5版本)

HTML部分:(沒什么內(nèi)容 放置一個(gè)按鈕調(diào)用函數(shù),js中調(diào)用實(shí)例即可供參考)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>自定義彈窗</title>
    <link rel="stylesheet" href="alert.css">
</head>
<body>
  
      <button>Click me</button>
      <script src="index.js"></script>
      <script>
        document.querySelector("button").addEventListener("click",()=>{
          new $Msg({
            content:"我的自定義彈窗好了",
            type:"success",
            cancle:function(){
              let cancle = new $Msg({
                content:"我是取消后的回調(diào)"
              })
            },
            confirm:function(){
              new $Msg({content:"我是確定后的回調(diào)"})
            }
          })
        })
      
      </script>
</body>
</html>

樣式部分:也放出來供參考,樣式可以根據(jù)自己的設(shè)計(jì)圖自行更改即可

/* 彈出框最外層 */
.msg__wrap {
    position: fixed;
    top: 50%;
    left: 50%;
    z-index: 10;
    transition: all .3s;
    transform: translate(-50%, -50%) scale(0, 0);
    max-width: 50%;
   
    background: #fff;
    box-shadow: 0 0 10px #eee;
    font-size: 10px;
  }
  
  /* 彈出框頭部 */
  .msg__wrap .msg-header {
    padding: 10px 10px 0 10px;
    font-size: 1.8em;
  }
  
  .msg__wrap .msg-header .msg-header-close-button {
    float: right;
    cursor: pointer;
  }
  
  /* 彈出框中部 */
  .msg__wrap .msg-body {
    padding: 10px 10px 10px 10px;
    display: flex;
  }
  
  /* 圖標(biāo) */
  .msg__wrap .msg-body .msg-body-icon{
    width: 80px;
  }
  
  .msg__wrap .msg-body .msg-body-icon div{
    width: 45px;
    height: 45px;
    margin: 0 auto;
    line-height: 45px;
    color: #fff;
    border-radius: 50% 50%;
    font-size: 2em;
  }
  
  .msg__wrap .msg-body .msg-body-icon .msg-body-icon-success{
    background: #32a323;
    text-align: center;
  }
  
  .msg__wrap .msg-body .msg-body-icon .msg-body-icon-success::after{
    content: "成";
  }
  
  .msg__wrap .msg-body .msg-body-icon .msg-body-icon-wrong{
    background: #ff8080;
    text-align: center;
  }
  
  .msg__wrap .msg-body .msg-body-icon .msg-body-icon-wrong::after{
    content: "誤";
  }
  
  .msg__wrap .msg-body .msg-body-icon .msg-body-icon-info{
    background: #80b7ff;
    text-align: center;
  }
  
  .msg__wrap .msg-body .msg-body-icon .msg-body-icon-info::after{
    content: "注";
  }
  
  /* 內(nèi)容 */
  .msg__wrap .msg-body .msg-body-content{
    min-width: 200px;
    font-size: 1.5em;
    word-break: break-all;
    display: flex;
    align-items: center;
    padding-left: 10px;
    box-sizing: border-box;
  }
  
  /* 彈出框底部 */
  .msg__wrap .msg-footer {
    padding: 0 10px 10px 10px;
    display: flex;
    flex-direction: row-reverse;
  }
  
  .msg__wrap .msg-footer .msg-footer-btn {
    width: 50px;
    height: 30px;
    border: 0 none;
    color: #fff;
    outline: none;
    font-size: 1em;
    border-radius: 2px;
    margin-left: 5px;
    cursor: pointer;
  }
  
  .msg__wrap .msg-footer .msg-footer-cancel-button{
    background-color: #ff3b3b;
  }
  
  .msg__wrap .msg-footer .msg-footer-cancel-button:active{
    background-color: #ff6f6f;
  }
  
  .msg__wrap .msg-footer .msg-footer-confirm-button{
    background-color: #4896f0;
  }
  
  .msg__wrap .msg-footer .msg-footer-confirm-button:active{
    background-color: #1d5fac;
  }
  
  /* 遮罩層 */
  .msg__overlay {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 5;
    background-color: rgba(0, 0, 0, .4);
    transition: all .3s;
    opacity: 0;
  }
  

CSS

JS部分:下面是最主要的部分,js方法及交互。自己封裝自定義組件均可以此為參考,封裝自己的組件。

/*
 *自定義彈窗
 */
//自執(zhí)行函數(shù) 形成封閉的作用域 避免全局污染 
//傳入windwo和document對(duì)象  相當(dāng)于將window和document作為了作用域中的局部變量,
//就不需要內(nèi)部函數(shù)沿著作用域鏈再查找到最頂層的window 提高運(yùn)行效率。
(function (window, document) {
    //定義一個(gè)構(gòu)造函數(shù)Msg 作為彈窗實(shí)例的構(gòu)造函數(shù)。
    let Msg = function (options) {
        //執(zhí)行初始化操作
        this._init(options);
    }

    //定義初始化方法 并對(duì)方法傳遞的參數(shù)進(jìn)行初始化
    Msg.prototype = {
        _init({
            content = "", //文本內(nèi)容
            type = "info", //信息類型
            useHTML = false, //是否解析html字符串
            showIcon = true, //是否展示彈窗圖標(biāo)
            confirm = null, //確認(rèn)后得回調(diào)
            cancle = null, //取消后得回調(diào)
            footer = true, //是否顯示底部的確認(rèn)按鈕
            header = true, //是否顯示頭部信息及關(guān)閉按鈕
            title = "提示", //彈窗標(biāo)題
            contentStyle = {}, //內(nèi)容樣式
            contentFontSize = "1.5em", //內(nèi)容字體大小
            btnName = ["確定", "取消"] //按鈕文字內(nèi)容
        }) {
            //將傳入的值綁定到this上 
            this.content = content;
            this.type = type;
            this.useHTML = useHTML;
            this.showIcon = showIcon;
            this.confirm = confirm;
            this.cancle = cancle;
            this.footer = footer;
            this.header = header;
            this.title = title;
            this.contentStyle = contentStyle;
            this.contentFontSize = contentFontSize;
            this.btnName = btnName;

            //執(zhí)行創(chuàng)建元素方法
            this._creatElement();
            //顯示彈窗及遮罩
            this._show({
                el: this._el,
                overlay: this._overlay
            });
            //綁定事件處理函數(shù)
            this._bind({
                el: this._el,
                overlay: this._overlay
            });
        },

        //創(chuàng)建彈窗元素方法
        _creatElement() {
            //創(chuàng)建最外層得包裹元素
            let wrap = document.createElement("div");
            wrap.className = "msg__wrap";

            //定義彈窗得兩個(gè)按鈕
            const [confirmBtnName, cancelBtnName] = this.btnName;

            //判斷是否顯示彈窗標(biāo)題
            const headerHTML = this.header ?
                `<div class="msg-header">
                        <span>${this.title}</span>
                        <span class="msg-header-close-button">×</span>
                    </div>` : "";

            //判斷是否顯示圖標(biāo)
            const iconHTML = this.showIcon ?
                `<div class="msg-body-icon">
                    <div class="msg-body-icon-${this.type}"></div>
                </div>` : "";

            //判斷是否顯示彈窗底部按鈕
            const footerHTML = this.footer ?
                `<div class="msg-footer">
                        <button class="msg-footer-btn msg-footer-cancel-button">${cancelBtnName}</button>
                        <button class="msg-footer-btn msg-footer-confirm-button">${confirmBtnName}</button>
                    </div>` : "";

            //拼接完整html
            const innerHTML = `${headerHTML}
            <div class="msg-body">
                ${iconHTML}
                <div class="msg-body-content"></div>
            </div>
            ${footerHTML}`;

            //將拼接的html賦值到wrap中
            wrap.innerHTML = innerHTML;

            //把自定義的樣式進(jìn)行合并
            const contentStyle = {
                fontSize: this.contentFontSize,
                ...this.contentStyle
            }

            //獲取內(nèi)容所屬DOM
            let content = wrap.querySelector(".msg-body .msg-body-content");
            //將傳過來的樣式添加到contentDOM
            for (const key in contentStyle) {
                if (contentStyle.hasOwnProperty(key)) {
                    content.style[key] = contentStyle[key];

                }
            }

            //給彈窗的conntent賦值
            if (this.useHTML) {
                content.innerHTML = this.content;
            } else {
                content.innerText = this.content;
            }

            //創(chuàng)建遮罩層
            let overlay = document.createElement("div");
            overlay.className = "msg__overlay";

            //把dom掛載到當(dāng)前實(shí)例上
            this._overlay = overlay;
            this._el = wrap;
        },

        //彈窗展現(xiàn)方法
        _show({
            el,
            overlay
        }) {
            //把彈窗的dom和遮罩插入到頁面中
            document.body.appendChild(el);
            document.body.appendChild(overlay);

            //將彈窗顯示出來 timeout進(jìn)行異步處理顯示動(dòng)畫
            setTimeout(() => {
                el.style.transform = "translate(-50%,-50%) scale(1,1)";
                overlay.style.opacity = "1";
            })
        },

        //關(guān)閉彈窗方法
        _close({
            el,
            overlay
        }) {
            //隱藏dom 
            el.style.transform = "translate(-50%,-50%) scale(0,0)";
            overlay.style.opcity = "0";
            //根據(jù)動(dòng)畫時(shí)間  動(dòng)畫完成再移除
            setTimeout(() => {

                //把彈窗的dom和遮罩移除
                document.body.removeChild(el)
                document.body.removeChild(overlay);
            }, 300);
        },

        //事件處理函數(shù),為DOM綁定事件
        _bind({
            el,
            overlay
        }) {
            //保存當(dāng)前this
            //const _this = this;

            const cancle = (e) => {
                this.cancle && this.cancle.call(this, e);
                //隱藏彈窗
                //hideMsg();
                this._close({
                    el,
                    overlay
                });
            }
            //確認(rèn)彈窗
            const confirm = (e) => {
                this.confirm && this.confirm.call(this, e);
                this._close({
                    el,
                    overlay
                });
            }


            //頂部關(guān)閉按鈕綁定事件
            if (this.header) {
                el.querySelector(".msg-header-close-button").addEventListener("click", cancle);
            }
            //彈窗底部?jī)蓚€(gè)按鈕事件監(jiān)聽
            if (this.footer) {
                el.querySelector(".msg-footer-cancel-button").addEventListener("click", cancle);
                el.querySelector(".msg-footer-confirm-button").addEventListener("click", confirm)
            }
        }


    }

    //將構(gòu)造函數(shù)暴露到window  可直接在全局作用域中訪問構(gòu)造函數(shù)
    window.$Msg = Msg;


})(window, document);

JS

到此,一個(gè)完整的自定義彈窗組件已完成,只需要引入該js以及css或者直接把相關(guān)代碼加到自己的公共js中即可直接調(diào)用,注意,構(gòu)造函數(shù)調(diào)用要用new.

下面是點(diǎn)擊之后彈窗圖效果(gif動(dòng)態(tài)圖):

覺得不錯(cuò)的,趕快動(dòng)手試試吧。紙上得來終覺淺,絕知此事要躬行。

海納百川,有容乃大;壁立千仞,無欲則剛。人要有胸懷方能成大事,不要被欲望所驅(qū)使,方能風(fēng)吹不動(dòng)浪打不搖。

不積跬步無以至千里,不積小流無以成江海。從事技術(shù)工作,要時(shí)刻學(xué)習(xí)積累,即使不能一專多能也應(yīng)術(shù)業(yè)有專攻,方能以不變應(yīng)萬變。

總結(jié)

以上是生活随笔為你收集整理的js实现自定义弹窗的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。