如何修改现有HTML、CSS、JavaScript代码实现垂直可调整大小拆分面板
你只需对代码做以下三处修改即可实现垂直方向的拆分面板效果:
1. 修改JavaScript逻辑
补充垂直方向的拖拽计算逻辑,修改后的完整JS代码如下:
// 拖拽移动处理函数 function dragElement(element, direction) { var md; // 存储鼠标按下时的初始信息 const first = document.getElementById("first"); const second = document.getElementById("second"); element.onmousedown = onMouseDown; function onMouseDown(e) { md = { e, offsetLeft: element.offsetLeft, offsetTop: element.offsetTop, firstWidth: first.offsetWidth, secondWidth: second.offsetWidth, // 新增存储两个面板的初始高度 firstHeight: first.offsetHeight, secondHeight: second.offsetHeight }; document.onmousemove = onMouseMove; document.onmouseup = () => { document.onmousemove = document.onmouseup = null; } } function onMouseMove(e) { var delta = { x: e.clientX - md.e.clientX, y: e.clientY - md.e.clientY }; if (direction === "H") // 水平方向逻辑 { delta.x = Math.min(Math.max(delta.x, -md.firstWidth), md.secondWidth); element.style.left = md.offsetLeft + delta.x + "px"; first.style.width = (md.firstWidth + delta.x) + "px"; second.style.width = (md.secondWidth - delta.x) + "px"; } else if (direction === "V") { // 新增垂直方向逻辑 delta.y = Math.min(Math.max(delta.y, -md.firstHeight), md.secondHeight); element.style.top = md.offsetTop + delta.y + "px"; first.style.height = (md.firstHeight + delta.y) + "px"; second.style.height = (md.secondHeight - delta.y) + "px"; } } } // 最后一个参数改为V启用垂直拖拽 dragElement(document.getElementById("separator"), "V");
2. 修改CSS样式
调整布局方向、分隔条样式和面板尺寸属性,修改后的完整CSS代码如下:
.splitter { width: 100%; height: 300px; /* 调整高度方便查看效果 */ display: flex; flex-direction: column; /* 弹性布局改为垂直方向 */ } #separator { cursor: row-resize; /* 光标改为上下调整样式 */ background-color: #aaa; /* 背景图改为横向三条线 */ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='10'><path d='M0 2 h30 M0 5 h30 M0 8 h30' fill='none' stroke='black'/></svg>"); background-repeat: no-repeat; background-position: center; width: 100%; /* 分隔条宽度占满 */ height: 10px; /* 分隔条高度改为10px */ -moz-user-select: none; -ms-user-select: none; user-select: none; } #first { background-color: #dde; height: 20%; /* 宽度属性改为高度 */ width: 100%; min-height: 10px; /* 最小宽度改为最小高度 */ } #second { background-color: #eee; height: 80%; /* 宽度属性改为高度 */ width: 100%; min-height: 10px; /* 最小宽度改为最小高度 */ }
3. 无需修改HTML结构
原有HTML代码可以直接沿用,不需要做任何调整。
内容的提问来源于stack exchange,提问作者Rihazz
相关产品推荐
相关产品推荐

