项目背景:react+ts+less 常见使用按钮来实现侧边菜单缩起/展开,现用代码实现侧边栏拖拽宽度改变。
具体代码实现:
... react 类组件 部分关键代码
constructor(props: any) {
super(props)
this.state = {
leftSideWidth: 300, // 侧边栏宽度
tempWidth: 300,
dragObject: {
x: 0,
y: 0
}
}
}
// 一般是在 mousedown 或者 dragstart 时触发
dragInit = (e: any) => {
this.setState({ dragObject: { x: e.pageX, y: e.pageY } })
window.addEventListener('mousemove', this.drag);
window.addEventListener('mouseup', this.dragEnd);
this.startDrag();
}
drag = (e: any) => {
this.onMove(e.pageX - this.state.dragObject.x, e.pageY - this.state.dragObject.y);
}
dragEnd = () => {
window.removeEventListener('mousemove', this.drag);
window.removeEventListener('mouseup', this.dragEnd);
this.setState({ dragObject: { x: 0, y: 0 } })
}
// 左侧拖动
onMove = (dx: any, dy: any) => {
let width = this.state.tempWidth + dx
let leftSideWidth = width < 200 ? 200 : width > 480 ? 480 : width // 最小200 最大480
this.setState({ leftSideWidth: leftSideWidth })
}
startDrag = () => {
this.setState({ tempWidth: this.state.leftSideWidth })
}
render() {
return (
<div className='pages'>
<div>
<div className='line-left' style={{ width: this.state.leftSideWidth + 'px' }}>
<h4>left</h4>
<div className="drag-line" onMouseDown={this.dragInit}></div>
</div>
</div>
<div>
<h5>context</h5>
</div>
</div>
);
}
样式关键部分:
cursor: col-resize;
可出现双向箭头样式
.line-left {
height: 100vh;
position: relative;
}
// 拖拽线
.drag-line {
width: 4px;
background: transparent;
cursor: col-resize;
z-index: 2;
top: 0;
bottom: 0;
right: 0;
position: absolute;
&:hover {
background-color: #bfbfbf;
}
}
最终效果图