萬盛學電腦網

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

jQuery 實作可拖曳、居中、動畫開關的自訂 Modal 彈窗元件

功能清單

  • 點擊按鈕開啟,遮罩淡入 + 彈窗縮放/位移動畫進場
  • 標題列可拖曳移動彈窗位置
  • 關閉鈕 / 遮罩點擊 / ESC 鍵 關閉,反向動畫離場
  • 登入表單驗證示範
  • 輸入框佔位符提示切換

HTML 結構

<button id="show" class="alter">彈窗</button>

<div class="box">          <!-- 遮罩層 -->
  <div class="box_content"> <!-- 彈窗主體 -->
    <div class="title">     <!-- 拖曳把手 -->
      <h3>登入會員系統</h3>
      <span id="close">×</span>
    </div>
    <div class="content">
      <form id="loginForm">
        <div class="field">
          <label for="username">帳號</label>
          <input type="text" id="username" name="username" placeholder="請輸入帳號" required>
        </div>
        <div class="field">
          <label for="pwd">密碼</label>
          <input type="password" id="pwd" name="pwd" placeholder="請輸入密碼" required>
        </div>
        <div class="field checkbox-row">
          <label><input type="checkbox" name="remember" checked> 下次自動登入</label>
          <a href="#" class="forgot">忘記密碼?</a>
        </div>
        <button type="submit" class="btn-login">登入</button>
      </form>
      <div class="other-login">
        <p>第三方登入</p>
        <ul><li>QQ</li><li>WeChat</li><li>GitHub</li></ul>
      </div>
    </div>
  </div>
</div>

CSS 精簡版(關鍵:flex 置中、transform 動畫)

* { box-sizing: border-box; margin: 0; padding: 0; }
.alter { padding: 10px 20px; cursor: pointer; }

.box {
    position: fixed; inset: 0; z-index: 10000;
    background: rgba(0,0,0,0.5); display: none;
    /* 進場動畫由 JS 控制 opacity */
}
.box_content {
    position: fixed; top: 50%; left: 50%;
    width: 350px; background: #fff; border-radius: 8px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 0; visibility: hidden;
    transition: transform 0.3s cubic-bezier(0.4,0,0.2,1), opacity 0.3s, visibility 0s 0.3s;
}
.box_content.open { transform: translate(-50%, -50%) scale(1); opacity: 1; visibility: visible; transition-delay: 0s; }

.title { height: 50px; line-height: 50px; background: #f5f5f5; border-radius: 8px 8px 0 0; padding: 0 20px; cursor: move; user-select: none; display: flex; justify-content: space-between; align-items: center; }
.title h3 { font-size: 16px; font-weight: 600; }
#close { font-size: 24px; color: #999; cursor: pointer; }
#close:hover { color: #333; }

.content { padding: 20px; }
.field { margin-bottom: 16px; }
.field label { display: block; margin-bottom: 6px; font-size: 14px; color: #666; }
.field input { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; }
.field input:focus { outline: none; border-color: #4490F7; box-shadow: 0 0 0 3px rgba(68,144,247,0.2); }
.checkbox-row { display: flex; justify-content: space-between; align-items: center; font-size: 13px; }
.forgot { color: #1B66C7; text-decoration: none; }
.forgot:hover { text-decoration: underline; }
.btn-login { width: 100%; padding: 12px; background: #4490F7; color: #fff; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }
.btn-login:hover { background: #559BFC; }

.other-login { margin-top: 20px; padding-top: 20px; border-top: 1px solid #eee; text-align: center; font-size: 13px; color: #999; }
.other-login ul { display: flex; justify-content: center; gap: 15px; margin-top: 10px; list-style: none; }
.other-login li { width: 36px; height: 36px; line-height: 36px; border-radius: 50%; background: #1B66C7; color: #fff; cursor: pointer; }

jQuery 模組化寫法

var Modal = (function($) {
    var $box = $('.box'), $content = $('.box_content'), $title = $('.title'), $close = $('#close'), $show = $('#show'), $form = $('#loginForm');
    var drag = { moving: false, offsetX: 0, offsetY: 0 };
    
    function open() {
        $box.fadeIn(200);
        requestAnimationFrame(function() { $content.addClass('open'); });
        $form[0].reset();
        $('#username').trigger('focus');
    }
    function close() {
        $content.removeClass('open');
        setTimeout(function() { $box.fadeOut(200); }, 300); // 等動畫結束
    }
    
    // 拖曳邏輯(滑鼠/觸控雙支援)
    $title.on('mousedown touchstart', function(e) {
        if (e.target === $close[0]) return; // 點關閉鈕不拖曳
        drag.moving = true;
        var pos = e.type === 'mousedown' ? e : e.originalEvent.touches[0];
        drag.offsetX = pos.clientX - $content.offset().left;
        drag.offsetY = pos.clientY - $content.offset().top;
        $title.css('cursor', 'grabbing');
    });
    $(document).on('mousemove touchmove', function(e) {
        if (!drag.moving) return;
        e.preventDefault();
        var pos = e.type === 'mousemove' ? e : e.originalEvent.touches[0];
        $content.css({ left: pos.clientX - drag.offsetX, top: pos.clientY - drag.offsetY, transform: 'none' }); // 拖曳時取消 transform 置中
    }).on('mouseup touchend', function() {
        drag.moving = false;
        $title.css('cursor', 'move');
    });
    
    // 事件綁定
    $show.on('click', open);
    $close.add($box).on('click', function(e) { if (e.target === this) close(); }); // 遮罩點擊關閉,但彈窗內點擊不關閉
    $(document).on('keydown', function(e) { if (e.key === 'Escape' && $content.hasClass('open')) close(); });
    $form.on('submit', function(e) {
        e.preventDefault();
        // 驗證邏輯...
        console.log('登入提交:', $(this).serialize());
        close();
    });
    
    // 公開 API
    return { open: open, close: close };
})(jQuery);

無障礙 (a11y) 補強

  • 開啟時:$content.attr({ 'role': 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'modal-title' }),焦點移至第一個輸入框。
  • 關閉時:焦點回到觸發按鈕 $show.trigger('focus')。
  • 焦點陷阱:在 keydown 中攔截 Tab/Shift+Tab 循環於彈窗內可聚焦元素。
copyright © 萬盛學電腦網 all rights reserved