萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 自訂 Modal 對話框元件實作(兩種模式)

需求背景

原生 alert/confirm 樣式固定、無法客製化。自行實作 Modal 可控制標題、內容、按鈕、回呼、遮罩、拖曳等。

模式一:完整版(含標題、內容區、按鈕列、遮罩)

var Modal = (function() {
  var defaults = {
    id: "modal_" + Date.now(),
    title: "",
    content: "",
    width: 400,
    height: "auto",
    buttons: ["confirm", "cancel"], // 可選 confirm, cancel
    onConfirm: null,
    onCancel: null
  };

  function create(opt) {
    var $overlay = $("#modal_overlay");
    if (!$overlay.length) {
      $overlay = $('

模式二:輕量浮動提示(無標題、定位於滑鼠/元素旁)

var Tooltip = (function() {
  return function(opt) {
    var $box = $('
').css({ position: "absolute", left: opt.left || 0, top: opt.top || 0, "z-index": 2000, border: "1px solid #ccc", background: "#fff", padding: "10px", width: opt.width || 200 }).appendTo(opt.parent || "body").hide(); $box.html(opt.content).fadeIn(200); return { close: function() { $box.fadeOut(200, function() { $(this).remove(); }); }, setContent: function(html) { $box.html(html); } }; }; })(); // 使用:滑鼠右鍵選單式提示 $(document).on("contextmenu", ".has-tip", function(e) { e.preventDefault(); Tooltip({ left: e.pageX, top: e.pageY, content: "操作選單...", width: 150 }); });

CSS 關鍵樣式

.modal_box { border: 1px solid #999; border-radius: 4px; background: #fff; box-shadow: 0 2px 10px rgba(0,0,0,.3); }
.modal_header { padding: 10px; border-bottom: 1px solid #eee; font-weight: bold; position: relative; }
.modal_close { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); text-decoration: none; font-size: 1.5em; }
.modal_content { padding: 15px; min-height: 50px; }
.modal_footer { padding: 10px; text-align: right; border-top: 1px solid #eee; }
.btn_confirm, .btn_cancel { margin-left: 8px; padding: 5px 15px; cursor: pointer; }
#modal_overlay { display: none; }
copyright © 萬盛學電腦網 all rights reserved