滑鼠按下記錄初始位置 → 移動時計算位移 → 更新元素 left/top → 滑鼠釋放結束。關鍵在於座標系轉換與邊界限制。
// HTML
<button id="show">顯示視窗</button>
<div class="win">
<div class="wTop"><span id="hidden">×</span></div>
<div class="content">視窗內容區</div>
</div>
// CSS
.win { position: absolute; width: 500px; height: 400px; background: #fff; border: 1px solid #ddd; box-shadow: 0 4px 12px rgba(0,0,0,0.15); display: none; }
.wTop { height: 40px; line-height: 40px; padding: 0 15px; background: #f5f5f5; border-bottom: 1px solid #eee; cursor: move; user-select: none; display: flex; justify-content: flex-end; }
.content { padding: 20px; height: calc(100% - 40px); overflow: auto; }
// JS
$(function() {
var $win = $('.win'), $handle = $('.wTop'), $show = $('#show'), $close = $('#hidden');
var dragging = false, startX, startY, initLeft, initTop;
// 1. 初始置中
function center() {
$win.css({ left: ($(window).width() - $win.outerWidth()) / 2, top: ($(window).height() - $win.outerHeight()) / 2 });
}
// 2. 拖曳邏輯
$handle.on('mousedown', function(e) {
dragging = true;
startX = e.clientX; startY = e.clientY;
initLeft = $win.position().left; initTop = $win.position().top;
$handle.css('cursor', 'grabbing');
});
$(document).on('mousemove', function(e) {
if (!dragging) return;
var dx = e.clientX - startX, dy = e.clientY - startY;
$win.css({ left: initLeft + dx, top: initTop + dy });
}).on('mouseup', function() {
dragging = false;
$handle.css('cursor', 'move');
});
// 3. 開關
$show.on('click', function() { center(); $win.fadeIn(200); });
$close.on('click', function() { $win.fadeOut(200); });
// 4. 視窗縮放時保持置中(可選)
$(window).on('resize', function() { if ($win.is(':visible')) center(); });
});
class DraggableModal {
constructor(options = {}) {
this.$el = $(options.template || this.defaultTemplate());
this.$handle = this.$el.find(options.handleSelector || '.modal-header');
this.$closeBtn = this.$el.find(options.closeSelector || '.modal-close');
this.containment = options.containment || 'window'; // 'window' | 'parent' | selector
this.bounds = options.bounds || { top: 0, left: 0, right: 0, bottom: 0 }; // 邊界偏移
this._dragging = false;
this._offset = { x: 0, y: 0 };
this._initEvents();
$('body').append(this.$el);
}
defaultTemplate() {
return `
`;
}
_initEvents() {
const $doc = $(document);
this.$handle.on('mousedown touchstart', (e) => this._onDragStart(e));
$doc.on('mousemove touchmove', (e) => this._onDragMove(e));
$doc.on('mouseup touchend', () => this._onDragEnd());
this.$closeBtn.on('click', () => this.hide());
this.$el.on('click', (e) => { if (e.target === this.$el[0]) this.hide(); }); // 遮罩關閉
}
_onDragStart(e) {
if ($(e.target).closest(this.$closeBtn).length) return;
this._dragging = true;
const pos = e.type === 'mousedown' ? e : e.originalEvent.touches[0];
const offset = this.$el.offset();
this._offset.x = pos.clientX - offset.left;
this._offset.y = pos.clientY - offset.top;
this.$handle.css('cursor', 'grabbing');
this.$el.addClass('dragging');
}
_onDragMove(e) {
if (!this._dragging) return;
e.preventDefault();
const pos = e.type === 'mousemove' ? e : e.originalEvent.touches[0];
let left = pos.clientX - this._offset.x;
let top = pos.clientY - this._offset.y;
// 邊界限制
const bounds = this._getBounds();
left = Math.max(bounds.left, Math.min(left, bounds.right - this.$el.outerWidth()));
top = Math.max(bounds.top, Math.min(top, bounds.bottom - this.$el.outerHeight()));
this.$el.css({ left, top, transform: 'none' }); // 拖曳時取消 CSS transform 置中
}
_onDragEnd() {
this._dragging = false;
this.$handle.css('cursor', 'move');
this.$el.removeClass('dragging');
}
_getBounds() {
if (this.containment === 'window') {
return { top: 0, left: 0, right: $(window).width(), bottom: $(window).height() };
}
// 可擴充 parent/selector 邏輯
return { top: -9999, left: -9999, right: 9999, bottom: 9999 };
}
show() {
this.$el.fadeIn(200);
this.center();
}
hide() {
this.$el.fadeOut(200);
}
center() {
this.$el.css({
left: ($(window).width() - this.$el.outerWidth()) / 2,
top: ($(window).height() - this.$el.outerHeight()) / 2,
transform: 'none'
});
}
setContent(html) {
this.$el.find('.modal-body').html(html);
}
destroy() {
this.$el.remove();
$(document).off('mousemove touchmove mouseup touchend');
}
}
// 使用
var modal = new DraggableModal({
handleSelector: '.modal-header',
closeSelector: '.modal-close',
containment: 'window'
});
modal.setContent('');
$('#openBtn').on('click', () => modal.show());
requestAnimationFrame 節流移動:高頻 mousemove 直接改 CSS 會導致佈局抖動。will-change: transform:提升合成層,拖曳更絲滑。touchstart/move/end 事件並行處理。