分隔条上下拖动 原生js

it2024-08-13  39

<!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: 800px; margin: 20px auto; } #top { width: 800px; height: 400px; background: #363634; position: absolute; right: 0; left: 0; } #bottom { margin-top: 420px; background: rgb(74, 62, 97); height: 100%; } #line { position: absolute; left: 0; right: 0; top: 400px; height: 4px; background: #924848; box-shadow: 0px 0px 8px #ccc; cursor: n-resize; z-index: 4; } </style> </head> <body> <div id="root"> <div id="top">上边部分</div> <div id="bottom">下边部分</div> <!-- 分隔条 --> <div id="line"></div> </div> </body> <script> // 改变分隔条上下高度所需常量 const topHeight = 400; // 上边部分高度 const bottomToTopGap = 20; // 下边部分与上边部分的距离 const lineHeight = 4; // 分隔条高度 const splitMinTop = 400; // 分隔条上边部分最小高度 const splitMaxTop = 808; // 分隔条上边部分最大高度 var oRoot = document.getElementById('root'), oTop = document.getElementById('top'), oBottom = document.getElementById('bottom'), oLine = document.getElementById('line'); window.onload = function () { oLine.onmousedown = handleLineMouseDown; }; // 分隔条操作 function handleLineMouseDown(e) { // 记录下初始位置的值 let disY = e.clientY; oLine.top = oLine.offsetTop; document.onmousemove = function (e) { let moveY = e.clientY - disY; // 鼠标拖动的偏移距离 let iT = oLine.top + moveY, // 分隔条相对父级定位的 left 值 maxT = oRoot.clientHeight - oLine.offsetHeight; iT < 0 && (iT = 0); iT > maxT && (iT = maxT); if (iT <= splitMinTop || iT >= splitMaxTop) return false; let topLineGap = splitMinTop - topHeight; // 分隔条距左边部分的距离 let oTopHeight = iT - topLineGap; let oBottomMarginTop = oTopHeight + lineHeight + bottomToTopGap; oLine.style.top = `${iT}px`; oTop.style.height = `${oTopHeight}px`; oBottom.style.marginTop = `${oBottomMarginTop}px`; return false; }; // 鼠标放开的时候取消操作 document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; }; } </script> </html>

 

最新回复(0)