<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resizable Layout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui-src/dist/css/layui.css">
<style>
.contain {
display: flex;
width: 100%; /* 容器宽度 */
height: 300px; /* 固定高度 */
position: relative;
box-sizing: border-box; /* 确保 padding 和 border 不影响宽度 */
}
.left {
min-width: 100px; /* 最小宽度 */
background-color: #f2f2f2;
transition: width 0.3s; /* 动画效果 */
}
.right {
background-color: #e6e6e6;
transition: width 0.3s; /* 动画效果 */
box-sizing: border-box; /* 确保 padding 和 border 不影响宽度 */
}
.divider {
width: 5px;
background-color: #ccc;
cursor: ew-resize; /* 拖动指针样式 */
position: absolute;
top: 0;
height: 100%; /* 高度与容器相同 */
left: 16.7%; /* 设置初始位置 */
z-index: 1000;
}
</style>
</head>
<body>
<div class="layui-row">
<div class="contain">
<div class="left layui-col-md2">左侧内容</div>
<div class="divider"></div>
<div class="right layui-col-md10">右侧内容</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/layui-src/dist/layui.js"></script>
<script>
const divider = document.querySelector('.divider');
const left = document.querySelector('.left');
const right = document.querySelector('.right');
const container = divider.parentElement; // 获取容器元素
let isDragging = false;
// 监听鼠标按下事件
divider.addEventListener('mousedown', (e) => {
isDragging = true;
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', stopResize);
document.body.style.cursor = 'ew-resize'; // 改变光标样式
});
// 拖动时调用的函数
function resize(e) {
e.preventDefault(); //阻止冒泡时间
if (!isDragging) return;
const containerRect = container.getBoundingClientRect();
const newLeftWidth = e.clientX - containerRect.left; // 计算新宽度
// 设置最小和最大宽度
if (newLeftWidth >= 100 && newLeftWidth <= containerRect.width - 105) { // 注意调整右边界的大小
left.style.width = `${newLeftWidth}px`; // 更新左侧宽度
right.style.width = `${containerRect.width - newLeftWidth - 5}px`; // 更新右侧宽度
divider.style.left = `${newLeftWidth}px`; // 更新分隔线位置
}
}
// 停止拖动时调用的函数
function stopResize() {
isDragging = false;
document.removeEventListener('mousemove', resize);
document.removeEventListener('mouseup', stopResize);
document.body.style.cursor = ''; // 恢复光标样式
}
</script>
</body>
</html>
js拖拽功能
于 2025-01-15 10:47:55 首次发布