需求就是像notion首页那样,拖拉侧栏右侧,便可改变侧栏宽度
以下是代码实现的效果
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.app {
width: 100%;
height: 100vh;
background-color: aliceblue;
display: flex;
}
#slide-bar {
width: 200px;
height: 100%;
background-color: #999;
color: red;
font-size: 50px;
text-align: center;
}
#drag-btn {
width: 6px;
height: 100%;
background-color: #fff;
cursor: w-resize;
}
.right {
height: 100%;
flex: 1;
background-color: antiquewhite;
color: red;
font-size: 50px;
text-align: center;
}
</style>
</head>
<body>
<div class="app">
<div id="slide-bar">侧栏</div>
<div id="drag-btn"></div>
<div class="right">右侧</div>
</div>
</body>
<script>
function init() {
dragSlidBar(20);
}
init();//执行
/**
* delay: 防抖时间
*/
function dragSlidBar(delay) {
const dragBtn = document.getElementById("drag-btn");
const slideBar = document.getElementById("slide-bar");
let slideBarWidth = 200;//默认为200
//鼠标按下
dragBtn.onmousedown = function (e) {
//记录鼠标开始位置
let startX = e.clientX;
//防抖初始时间
let init_time = 0;
//给得是document绑定事件
document.onmousemove = function (e) {
// 防抖
let now_time = new Date();//现在时间
if (now_time - init_time > delay) {//满足时间则执行
init_time = now_time;
//记录鼠标位置
let endX = e.clientX;
//计算鼠标移动距离
let moveX = endX - startX;
// 更新鼠标初始位置
startX = endX;
// 更新盒子宽度
slideBarWidth += moveX
// 边界值处理
if (slideBarWidth < 200) {
slideBarWidth = 200;
}
if (slideBarWidth > 400) {
slideBarWidth = 400
}
slideBar.style.width = slideBarWidth + 'px';
}
return false;//阻止默认事件
};
//解除事件
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
// 释放鼠标
dragBtn.releaseCapture && dragBtn.releaseCapture();
};
// 捕获鼠标
dragBtn.setCapture && dragBtn.setCapture();
return false;//阻止默认事件
};
}
</script>
</html>
嗯嗯,就这样咯,有问题请指正;
觉得有用就给个赞吧