js实现页面左右调节
实现页面左右调节的JavaScript方法
使用CSS和JavaScript控制布局
通过CSS设置页面容器为flex布局,结合JavaScript动态调整左右分栏的宽度比例。HTML结构需包含主容器和左右分栏:
<div class="container">
<div class="left-panel" id="leftPanel">左侧内容</div>
<div class="divider" id="divider"></div>
<div class="right-panel">右侧内容</div>
</div>
.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;
}
const divider = document.getElementById('divider');
const leftPanel = document.getElementById('leftPanel');
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 newLeftWidth = (e.clientX / containerWidth) * 100;
leftPanel.style.flex = `0 0 ${newLeftWidth}%`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
document.body.style.cursor = '';
});
使用第三方库实现拖拽调节
引入split.js等专门库可快速实现分栏拖拽功能:

<script src="https://unpkg.com/split.js/dist/split.min.js"></script>
Split(['#leftPanel', '#rightPanel'], {
sizes: [50, 50],
minSize: 100,
gutterSize: 10,
cursor: 'col-resize'
});
响应式布局增强
添加媒体查询确保移动设备上的可用性:

@media (max-width: 768px) {
.container {
flex-direction: column;
}
.divider {
width: 100%;
height: 10px;
cursor: row-resize;
}
}
保存用户偏好
使用localStorage存储用户调整后的宽度比例:
// 存储设置
leftPanel.addEventListener('mouseup', () => {
const flexValue = leftPanel.style.flex;
localStorage.setItem('panelRatio', flexValue);
});
// 加载设置
window.addEventListener('load', () => {
const savedRatio = localStorage.getItem('panelRatio');
if (savedRatio) leftPanel.style.flex = savedRatio;
});
触屏设备支持
为触摸事件添加相应处理:
divider.addEventListener('touchstart', (e) => {
isDragging = true;
});
document.addEventListener('touchmove', (e) => {
if (!isDragging) return;
const touch = e.touches[0];
const containerWidth = divider.parentNode.offsetWidth;
const newLeftWidth = (touch.clientX / containerWidth) * 100;
leftPanel.style.flex = `0 0 ${newLeftWidth}%`;
});
document.addEventListener('touchend', () => {
isDragging = false;
});






