js实现页面左右调节
使用CSS Flexbox布局
通过Flexbox可以轻松实现左右分栏布局,结合JavaScript动态调整宽度。HTML结构需包含一个容器和两个子元素:
<div class="container">
<div class="left-panel" id="leftPanel">左侧内容</div>
<div class="divider" id="divider"></div>
<div class="right-panel" id="rightPanel">右侧内容</div>
</div>
CSS样式设置Flexbox基础布局和拖拽条样式:
.container {
display: flex;
height: 100vh;
}
.left-panel {
flex: 1;
background: #f0f0f0;
}
.right-panel {
flex: 1;
background: #e0e0e0;
}
.divider {
width: 10px;
background: #ccc;
cursor: col-resize;
}
实现拖拽交互逻辑
JavaScript部分处理鼠标事件来实现宽度调整:
const divider = document.getElementById('divider');
const leftPanel = document.getElementById('leftPanel');
const rightPanel = document.getElementById('rightPanel');
let isDragging = false;
divider.addEventListener('mousedown', (e) => {
isDragging = true;
document.body.style.cursor = 'col-resize';
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const containerWidth = divider.parentNode.offsetWidth;
const leftWidth = e.clientX - leftPanel.getBoundingClientRect().left;
const rightWidth = containerWidth - leftWidth - 10; // 10是分隔条宽度
leftPanel.style.flex = `0 0 ${leftWidth}px`;
rightPanel.style.flex = `0 0 ${rightWidth}px`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
document.body.style.cursor = '';
});
使用Grid布局替代方案
CSS Grid布局也可以实现类似效果,适合更复杂的布局需求:
.container {
display: grid;
grid-template-columns: 1fr 10px 1fr;
height: 100vh;
}
调整JavaScript中的宽度计算逻辑:
const container = document.querySelector('.container');
// mousemove事件处理中修改为:
const leftWidth = (e.clientX / container.offsetWidth) * 100;
container.style.gridTemplateColumns = `${leftWidth}% 10px ${100 - leftWidth}%`;
添加平滑过渡效果
在CSS中添加过渡属性提升用户体验:
.left-panel, .right-panel {
transition: flex 0.2s ease;
}
/* 或Grid布局时 */
.container {
transition: grid-template-columns 0.2s ease;
}
边界条件处理
为防止面板过小,可添加最小宽度限制:
// 在mousemove事件中添加约束
const minWidth = 100; // 最小100px
const leftWidth = Math.max(minWidth, e.clientX - leftPanel.getBoundingClientRect().left);
const rightWidth = Math.max(minWidth, containerWidth - leftWidth - 10);
响应式布局考虑
针对移动设备可以添加媒体查询自动切换布局:
@media (max-width: 768px) {
.container {
flex-direction: column;
}
.divider {
width: 100%;
height: 10px;
cursor: row-resize;
}
}






