
splitter
【原理】:
- 定位
分為3個部分:左邊部分、分隔條、右邊部分,左邊部分與分隔條采用絕對定位。
- 事件
監(jiān)聽分隔條的 onmousedown 、onmousemove 、onmouseup 事件, onmousedown 記錄下分隔條的初始位置,onmousemove 進行計算,onmousedown 的時候取消操作。
- 位置計算
見代碼注釋。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>分隔條左右拖動 splitter</title>
<style>
#root {
position: relative;
width: 800px;
height: 300px;
margin: 20px auto;
}
#left {
width: 200px;
background: #ffdd40;
position: absolute;
top: 0;
bottom: 0;
}
#right {
margin-left: 220px;
background: pink;
height: 100%;
}
#line {
position: absolute;
top: 0;
bottom: 0;
left: 209px;
width: 4px;
background: #e7e7e7;
box-shadow: 0px 0px 8px #ccc;
cursor: w-resize;
}
</style>
</head>
<body>
<center>左右拖動分隔條改變顯示區(qū)域?qū)挾?lt;span id="msg"></span></center>
<div id="root">
<div id="left">左邊部分</div>
<div id="right">右邊部分</div>
<!-- 分隔條 -->
<div id="line"></div>
</div>
</body>
<script>
// 改變分隔條左右寬度所需常量
const leftWidth = 200; // 左邊部分寬度
const rightToLeftGap = 20; // 右邊部分與左邊部分的距離
const lineWidth = 4; // 分隔條寬度
const splitMinLeft = 209; // 分隔條左邊部分最小寬度
const splitMaxLeft = 408; // 分隔條左邊部分最大寬度
var oRoot = document.getElementById('root'),
oLeft = document.getElementById('left'),
oRight = document.getElementById('right'),
oLine = document.getElementById('line');
window.onload = function () {
oLine.onmousedown = handleLineMouseDown;
};
// 分隔條操作
function handleLineMouseDown(e) {
// 記錄下初始位置的值
let disX = e.clientX;
oLine.left = oLine.offsetLeft;
document.onmousemove = function (e) {
let moveX = e.clientX - disX; // 鼠標拖動的偏移距離
let iT = oLine.left + moveX, // 分隔條相對父級定位的 left 值
maxT = oRoot.clientWidth - oLine.offsetWidth;
iT < 0 && (iT = 0);
iT > maxT && (iT = maxT);
if (iT <= splitMinLeft || iT >= splitMaxLeft) return false;
let leftLineGap = splitMinLeft - leftWidth; // 分隔條距左邊部分的距離
let oLeftWidth = iT - leftLineGap;
let oRightMarginLeft = oLeftWidth + lineWidth + rightToLeftGap;
oLine.style.left = `${iT}px`;
oLeft.style.width = `${oLeftWidth}px`;
oRight.style.marginLeft = `${oRightMarginLeft}px`;
return false;
};
// 鼠標放開的時候取消操作
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
}
</script>
</html>
? Demo