這是一個很樸素但實用的元件:拖動中間那條細bar,就能改變左右兩側面板的寬度。
<script src="https://code.jquery.com/jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function bindResize(el) {
var els = document.getElementById('menu').style;
var x = 0;
$(el).mousedown(function (e) {
// 記錄滑鼠按下瞬間與元素左界的差值
x = e.clientX - el.offsetWidth - $("#menu").width();
el.setCapture ? (
el.setCapture(),
el.onmousemove = function (ev) { mouseMove(ev || event); },
el.onmouseup = mouseUp
) : (
$(document).bind("mousemove", mouseMove).bind("mouseup", mouseUp)
);
e.preventDefault(); // 避免選取到文字
});
function mouseMove(e) {
els.width = e.clientX - x + 'px';
}
function mouseUp() {
el.releaseCapture ? (
el.releaseCapture(),
el.onmousemove = el.onmouseup = null
) : (
$(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp)
);
}
}
// 讓左右兩欄填滿視窗扣除頁首的高度
var divResize = function () {
var totalHeight = $("html").height();
var topHeight = $("#top").height();
$("#menu").height(totalHeight - topHeight);
$("#rightbar").height(totalHeight - topHeight);
}
$(function () {
divResize();
$(window).resize(divResize);
bindResize(document.getElementById('rightbar'));
});
</script>
<div id="top" style="width:100%; height:80px;"></div>
<div id="menu" class="content"><span>待拖拽的div</span></div>
<div id="rightbar" style="width:2px; background:#cccccc; cursor:e-resize; float:left;"></div>
核心觀念只有一個:在 mousedown 時記下滑鼠位置與元素寬度的差值 x,之後 mousemove 只要用 滑鼠目前位置 - x 就是新寬度。mouseup 時記得解除 mousemove 監聽,否則放開滑鼠後仍會持續縮放。
setCapture/releaseCapture 是 IE 的滑鼠捕捉機制,用以處理滑鼠移出元素範圍的情形;現代瀏覽器可用 pointer events 或直接在 document 上綁 mousemove 取代,程式會單純不少。另外若要限制最小寬度,可在 mouseMove 中加上 Math.max/min 夾住結果。