js弹窗组件sweetalert2使用

经常会用到sweetalert2这个弹出层组件,整理记录下。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link href="../plugins/sweetalert2/sweetalert2.min.css" rel="stylesheet" />
  </head>
  <body>
    <button onclick="app.msg()">简单消息</button>
    <button onclick="app.showSuccess()">成功</button>
    <button onclick="app.showError()">错误</button>
    <button onclick="app.showInfo()">信息</button>
    <button onclick="app.showWarning()">警告</button>
    <button onclick="app.confirm()">确认框</button>
    <button onclick="app.fullScreen()">全屏</button>

    <br />
    <br />
    <button onclick="app.input_text()">文本框</button>
    <button onclick="app.input_email()">Email</button>
    <button onclick="app.input_url()">URL</button>
    <button onclick="app.input_password()">密码框</button>
    <button onclick="app.input_textarea()">文本域</button>
    <button onclick="app.input_select()">下拉菜单</button>
    <button onclick="app.input_radio()">单选框</button>
    <button onclick="app.input_checkbox()">复选框</button>
    <button onclick="app.input_date()">日期</button>
  </body>
  <script src="../plugins/sweetalert2/sweetalert2.all.min.js"></script>
  <script>
    const gbl_alert = {
      showBasicMsg: (title) => {
        Swal.fire(title);
      },

      showTypeMsg: (icon, title, timer = 0, callback_next = () => {}) => {
        const Toast = Swal.mixin({
          toast: true,
          position: "center",
          showConfirmButton: false,
          showCloseButton: true,

          timer: timer,
          timerProgressBar: true,
        });
        //type列表 warning error success info question
        Toast.fire({
          icon: icon,
          title: title,
        }).then((result) => {
          if (result.isDismissed) {
            callback_next();
          }
        });
      },

      showConfirmMsg: (title, text, callback_confirm, callback_deny = () => {}) => {
        Swal.fire({
          title: title,
          text: text,
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          backdrop: true,
          allowOutsideClick: false,
          allowEscapeKey: false,
          allowEnterKey: false,
        }).then((result) => {
          if (result.isConfirmed) {
            callback_confirm();
          } else {
            callback_deny();
          }
        });
      },

      showContentFullSCreen: (url) => {
        Swal.fire({
          html: `<iframe src="${url}" frameborder="0" width="100%" height="600px"></iframe>`,
          showConfirmButton: false,
          showCloseButton: true,
          backdrop: true,
          allowOutsideClick: false,
          allowEscapeKey: false,
          allowEnterKey: false,
          grow: "fullscreen",
        });
      },

      input: async (type, title, label_text, inputPlaceholder, initialValue = "", params = {}) => {
        let input_val = "";
        if (["text", "password", "textarea", "checkbox"].indexOf(type) !== -1) {
          const { value: inputValue } = await Swal.fire({
            title: title,
            input: type,
            inputLabel: label_text,
            inputValue: type == "checkbox" ? 1 : initialValue,
            inputPlaceholder: inputPlaceholder,
            showCancelButton: true,
            inputValidator: (value) => {
              return !value && "不能为空";
            },
          });
          input_val = inputValue;
        } else if (["email", "url"].indexOf(type) !== -1) {
          const { value: inputValue } = await Swal.fire({
            title: title,
            input: type,
            inputLabel: label_text,
            inputValue: initialValue,
            inputPlaceholder: inputPlaceholder,
            validationMessage: type == "email" ? "不合法的Email格式" : "不合法的URL格式",
            showCancelButton: true,
          });
          input_val = inputValue;
        } else if (["select", "radio"].indexOf(type) !== -1) {
          const { value: inputValue } = await Swal.fire({
            title: title,
            input: type,
            inputOptions: params["options"],
            inputPlaceholder: inputPlaceholder,
            showCancelButton: true,
            inputValidator: (value) => {
              return !value && "不能为空";
            },
          });
          input_val = inputValue;
        } else if (["checkbox"].indexOf(type) !== -1) {
          const { value: inputValue } = await Swal.fire({
            title: title,
            input: type,
            inputLabel: label_text,
            inputValue: type == "checkbox" ? 1 : initialValue,
            inputPlaceholder: inputPlaceholder,
            showCancelButton: true,
            inputValidator: (value) => {
              return !value && "不能为空";
            },
          });
          input_val = inputValue;
        } else if (type == "date") {
          const { value: inputValue } = await Swal.fire({
            title: title,
            input: "date",
            didOpen: () => {
              const today = new Date().toISOString();
              Swal.getInput().min = today.split("T")[0];
            },
          });
          input_val = inputValue;
        }

        if (input_val) {
          console.log(input_val);
        }
      },
    };

    const app = {
      msg: () => gbl_alert.showBasicMsg("hello"),
      showSuccess: () =>
        gbl_alert.showTypeMsg("success", "操作成功", 3000, function () {
          console.log("alert closed");
        }),
      showError: () => gbl_alert.showTypeMsg("error", "操作失败", 0),
      showInfo: () => gbl_alert.showTypeMsg("info", "新数据", 0),
      showWarning: () => gbl_alert.showTypeMsg("warning", "显示有误", 0),
      confirm: () =>
        gbl_alert.showConfirmMsg(
          "确定要删除吗?",
          "删除后不可恢复",
          function () {
            console.log("confirmed");
          },
          function () {
            console.log("canceled");
          }
        ),
      fullScreen: () => gbl_alert.showContentFullSCreen("../files/example_015.pdf"),
      input_text: () => gbl_alert.input("text", "请输入你的名字", "名字", "输入你的名字"),
      input_email: () => gbl_alert.input("email", "请输入你的邮箱", "邮箱", "输入你的邮箱"),
      input_url: () => gbl_alert.input("url", "请输入URL地址", "URL地址", "输入URL地址"),
      input_password: () => gbl_alert.input("password", "请输入密码", "密码", "输入密码"),
      input_textarea: () => gbl_alert.input("textarea", "请输入备注", "备注", "输入备注"),
      input_select: () =>
        gbl_alert.input("select", "请选择喜欢的食物", "喜欢的食物", "请选择喜欢的食物", "", {
          options: {
            Fruits: {
              apples: "Apples",
              oranges: "Oranges",
            },
            Vegetables: {
              broccoli: "Broccoli",
              carrot: "Carrot",
            },
            icecream: "Ice cream",
          },
        }),
      input_radio: () =>
        gbl_alert.input("radio", "请选择喜欢的颜色", "喜欢的颜色", "选择喜欢的颜色", "", {
          options: {
            "#ff0000": "Red",
            "#00ff00": "Green",
            "#0000ff": "Blue",
          },
        }),
      input_checkbox: () => gbl_alert.input("checkbox", "合同条款", "是否同意", "是否同意"),
      input_date: () => gbl_alert.input("date", "请输入日期", "日期", "输入日期"),
    };
  </script>
</html>

简单消息

带图标的消息

需确认的消息

输入框

选择框

可验证输入

单选框

复选框

 

posted @   carol2014  阅读(237)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示