點擊彈窗標題區域,可在視口內自由拖動彈窗位置,鬆開鼠標固定。支援邊界檢測,防止拖出可視區。
<!-- 遮罩層 -->
<div class="modal-background"></div>
<!-- 彈窗主體 -->
<div class="modal-window">
<div class="head">
<center>按住此處拖動我</center>
</div>
<div class="content">這裡是彈窗內容</div>
</div>
.modal-background {
background-color: #999;
bottom: 0; left: 0; right: 0; top: 0;
opacity: 0.3; position: fixed; z-index: 1100;
}
.modal-window {
background: #fff;
border: 1px solid #6B94AD;
box-shadow: 5px 5px 5px #6B94AD;
font-family: 'Microsoft YaHei'; font-size: 12px;
width: 320px; height: 120px;
position: fixed; z-index: 1110;
left: 50%; top: 50%;
margin-left: -160px; margin-top: -60px; /* 居中修正 */
}
.modal-window .head {
height: 25px; color: #fff; font-weight: 600;
background: linear-gradient(to bottom, #4A8CC5, #2963A5);
cursor: move; /* 提示可拖動 */
user-select: none; /* 禁止選中文字 */
}
.modal-window .head center { padding-top: 2px; }
/* 可選:不同尺寸的彈窗通過追加類覆蓋尺寸 */
.list-window { width: 600px; height: 400px; margin-left: -300px; margin-top: -200px; }
var left, top, $this;
$(document).delegate('.modal-window .head', 'mousedown', function(e) {
// 記錄初始鼠標位置
left = e.clientX;
top = e.clientY;
$this = $(this).css('cursor', 'move');
// 防止文字被選中
e.preventDefault();
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
// IE setCapture / 標準綁定 document 事件
if (this.setCapture) {
this.setCapture();
this.onmousemove = function(ev) { mouseMove(ev || event); };
this.onmouseup = mouseUp;
} else {
$(document).bind('mousemove', mouseMove).bind('mouseup', mouseUp);
}
});
function mouseMove(e) {
var target = $this.parents('.modal-window');
// 計算新位置
var l = Math.max((e.clientX - left + Number(target.css('margin-left').replace(/px$/, '')) || 0), -target.position().left);
var t = Math.max((e.clientY - top + Number(target.css('margin-top').replace(/px$/, '')) || 0), -target.position().top);
// 邊界限制
l = Math.min(l, $(window).width() - target.width() - target.position().left);
t = Math.min(t, $(window).height() - target.height() - target.position().top);
// 更新記錄點
left = e.clientX;
top = e.clientY;
// 應用新位置
target.css({ 'margin-left': l, 'margin-top': t });
}
function mouseUp(e) {
var el = $this.css('cursor', 'default').get(0);
if (el.releaseCapture) {
el.releaseCapture();
el.onmousemove = el.onmouseup = null;
} else {
$(document).unbind('mousemove', mouseMove).unbind('mouseup', mouseUp);
}
}
mousemove/mouseup 綁定到 document,解決鼠標移動過快脫離彈窗導致事件丟失的問題。clientX/Y 減去按下時的座標,得到偏移量,加上彈窗原有 margin-left/top 得到新位置。Math.max/min 確保彈窗不超出視口邊界。setCapture/releaseCapture 讓元素獨佔鼠標事件,現代瀏覽器用 document 綁定替代。在 mouseMove 中同時修改 target.width()/height() 即可實現縮放手柄,邏輯完全一致。
$.fn.drag = function(options) {
// ... 將上述邏輯封裝,支援 boundaryElem、dragStart/dragMove/dragEnd 回調
// 使用示例:
// $('.drag-elem').drag({ boundaryElem: '#boundary' });
};
完整插件代碼請參考原文末尾,已處理邊界、圖片拖拽默認行為阻止、文字選中阻止等細節。