萬盛學電腦網

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

jQuery 拖拽插件實現:從零構建跨瀏覽器可復用拖拽組件

插件設計目標

  • 零依賴核心邏輯(僅依賴 jQuery 事件系統)
  • 支持多元素同時拖拽
  • 層級管理(點擊置頂)
  • 視覺反饋(透明度、游標變化)
  • 邊界約束(可選)
  • 事件鉤子(start/move/end)

完整插件代碼


;(function($) {
    'use strict';
    
    // 全局狀態
    let $activeEl = null;     // 當前拖拽元素
    let zIndexBase = 1000;    // 基礎 z-index
    let startOffset = { x: 0, y: 0 }; // 鼠標相對元素偏移
    
    // 文檔級事件(全局單例,極致性能)
    const $doc = $(document)
        .on('mousemove.drag', function(e) {
            if (!$activeEl) return;
            
            const left = e.pageX - startOffset.x;
            const top  = e.pageY - startOffset.y;
            
            // 可選:邊界約束
            // const maxX = $(window).width()  - $activeEl.outerWidth();
            // const maxY = $(window).height() - $activeEl.outerHeight();
            // $activeEl.css({ left: Math.max(0, Math.min(left, maxX)), top: Math.max(0, Math.min(top, maxY)) });
            
            $activeEl.css({ left, top }); // 直接定位
        })
        .on('mouseup.drag', function() {
            if (!$activeEl) return;
            $activeEl.removeClass('drag-active').trigger('dragend');
            $activeEl = null;
        });
    
    // 插件定義
    $.fn.myDrag = function(options) {
        const opts = $.extend({
            handle: null,        // 拖拽手柄選擇器(為 null 則整個元素可拖拽)
            containment: 'window', // 'window' | 'parent' | selector | false
            cursor: 'move',      // 拖拽時游標
            opacity: 0.8,        // 拖拽時透明度
            zIndex: 1000,        // 起始 z-index
            onStart: $.noop,     // 開始回調
            onMove: $.noop,      // 移動回調
            onEnd: $.noop        // 結束回調
        }, options);
        
        return this.each(function() {
            const $el = $(this).css({ position: 'absolute', cursor: 'move' });
            const $handle = opts.handle ? $el.find(opts.handle) : $el;
            
            $handle.on('mousedown.drag', function(e) {
                // 忽略右鍵、中鍵、input/textarea 等表單元素
                if (e.which !== 1 || $(e.target).is('input,textarea,select,button,a')) return;
                
                e.preventDefault(); // 防止文字選中
                
                $activeEl = $el
                    .addClass('drag-active')
                    .css({ 
                        zIndex: opts.zIndex++, 
                        opacity: opts.opacity,
                        cursor: opts.cursor
                    })
                    .trigger('dragstart', e);
                
                // 計算偏移:鼠標頁面座標 - 元素當前左上角
                const offset = $el.offset();
                startOffset.x = e.pageX - offset.left;
                startOffset.y = e.pageY - offset.top;
                
                opts.onStart.call($el[0], e);
            });
        });
    };
    
    // 暴露全局停用方法(極少用)
    $.myDrag = { disable: () => $doc.off('.drag') };
    
})(jQuery);

CSS 配合


.drag-active {
    /* 拖拽時樣式:透明度、陰影、層級由 JS 動態設置 */
    user-select: none; /* 防止選中文字 */
    pointer-events: none; /* 關鍵:防止鼠標事件穿透到下層元素 */
}
.drag-handle { cursor: move; } /* 手柄樣式 */

使用示例


<style>
.draggable { 
    width: 120px; height: 120px; 
    background: #3498db; color: white; 
    display: flex; align-items: center; justify-content: center;
    border-radius: 8px; font-weight: bold;
    position: absolute; /* 必須 */
}
</style>

<div id="drag-area" style="position:relative; width:100%; height:400px; border:2px dashed #ddd;">
    <div class="draggable" style="left:20px; top:20px;">拖拽 1</div>
    <div class="draggable" style="left:160px; top:20px;">拖拽 2</div>
    <div class="draggable" style="left:300px; top:20px;">拖拽 3</div>
</div>

<script>
$('.draggable').myDrag({
    containment: '#drag-area', // 限制在父容器內
    onStart: function(e) { console.log('開始:', this.id || this.className); },
    onMove: function(e) { /* 實時位置可獲取 $(this).position() */ },
    onEnd: function(e) { console.log('結束位置:', $(this).position()); }
});

// 動態新增也生效
$('#addBtn').click(() => {
    $('
新項
') .css({ left: 20, top: 20 }) .appendTo('#drag-area') .myDrag({ containment: '#drag-area' }); }); </script>

原生 JS 替代方案(無 jQuery 依賴)


class VanillaDrag {
    static #active = null;
    static #zBase = 1000;
    static #offset = { x: 0, y: 0 };
    
    constructor(el, options = {}) {
        this.el = el;
        this.opts = Object.assign({
            handle: null,
            containment: null,
            onStart: () => {},
            onMove: () => {},
            onEnd: () => {}
        }, options);
        
        this._bind();
    }
    
    _bind() {
        const handle = this.opts.handle ? this.el.querySelector(this.opts.handle) : this.el;
        handle.style.cursor = 'move';
        this.el.style.position = 'absolute';
        
        handle.addEventListener('mousedown', e => this._onDown(e));
    }
    
    _onDown(e) {
        if (e.button !== 0) return; // 只處理左鍵
        if (e.target.closest('input,textarea,select,button,a')) return;
        
        e.preventDefault();
        VanillaDrag.#active = this;
        this.el.classList.add('drag-active');
        this.el.style.zIndex = VanillaDrag.#zBase++;
        this.el.style.opacity = '0.8';
        
        const rect = this.el.getBoundingClientRect();
        VanillaDrag.#offset.x = e.clientX - rect.left;
        VanillaDrag.#offset.y = e.clientY - rect.top;
        
        document.addEventListener('mousemove', this._onMove);
        document.addEventListener('mouseup', this._onUp);
        this.opts.onStart(e);
    }
    
    _onMove = (e) => {
        if (VanillaDrag.#active !== this) return;
        
        let left = e.clientX - VanillaDrag.#offset.x;
        let top  = e.clientY - VanillaDrag.#offset.y;
        
        // 邊界約束
        if (this.opts.containment) {
            const container = typeof this.opts.containment === 'string' 
                ? document.querySelector(this.opts.containment) 
                : this.opts.containment;
            if (container) {
                const cRect = container.getBoundingClientRect();
                const eRect = this.el.getBoundingClientRect();
                left = Math.max(cRect.left, Math.min(left, cRect.right - eRect.width));
                top  = Math.max(cRect.top,  Math.min(top,  cRect.bottom - eRect.height));
            }
        }
        
        this.el.style.left = left + 'px';
        this.el.style.top = top + 'px';
        this.opts.onMove(e);
    };
    
    _onUp = () => {
        if (VanillaDrag.#active !== this) return;
        this.el.classList.remove('drag-active');
        this.el.style.opacity = '';
        document.removeEventListener('mousemove', this._onMove);
        document.removeEventListener('mouseup', this._onUp);
        this.opts.onEnd();
        VanillaDrag.#active = null;
    };
    
    destroy() {
        this.el.removeEventListener('mousedown', this._onDown);
    }
}

// 使用
document.querySelectorAll('.draggable').forEach(el => new VanillaDrag(el));

總結

拖拽交互的核心是鼠標按下 → 記錄偏移 → 移動時按頁面座標定位 → 鬆開釋放。jQuery 版利用文檔級事件委託極致性能;原生版用類封裝狀態,無依賴、體積極小。關鍵細節:**pointer-events: none 防止穿透、zIndex 管理層級、邊界約束、表單元素排除、動態元素支持**。根據項目技術棧選擇合適方案即可。

copyright © 萬盛學電腦網 all rights reserved