1 Star 0 Fork 0

yzishan / webs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
dragDiv.html 3.13 KB
一键复制 编辑 原始数据 按行查看 历史
yangzishan 提交于 2024-01-09 17:56 . 啊大大
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.box {
width: 100%;
height: 300px;
display: flex;
}
/*左侧div样式*/
.left {
width: calc(30% - 5px); /*左侧初始化宽度*/
height: 100%;
background: #d6d6d6;
}
/*拖拽区div样式*/
.resize {
cursor: col-resize;
position: relative;
background-color: yellow;
width: 5px;
height: 300px;
background-size: cover;
background-position: center;
font-size: 32px;
}
/*拖拽区鼠标悬停样式*/
.resize:hover {
background-color: #444444;
}
/*右侧div'样式*/
.mid {
width: 70%; /*右侧初始化宽度*/
height: 100%;
background-color: red;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="left" id="left">
<!--左侧div内容-->
</div>
<!-- 通过一个 div 来充当区域边框实现拖动 -->
<div id="resize" class="resize" title="收缩侧边栏">
</div>
<div class="mid" id="right">
<!--右侧div内容-->
</div>
</div>
<script>
let resize = document.getElementById('resize');
let left = document.getElementById('left');
let mid = document.getElementById('right');
let box = document.getElementById('box');
// 鼠标按下事件
resize.onmousedown = function (e) {
// 记录坐标起始位置
let startX = e.clientX;
// 左边元素起始宽度
left.left = left.offsetWidth;
console.log('宽度:',resize.left);
// 鼠标拖动事件
document.onmousemove = function (e) {
// 鼠标拖动的终止位置
let endX = e.clientX;
// (endx-startx)= 移动的距离。resize.left + 移动的距离=左边区域最后的宽度
let moveLen = left.left + (endX - startX);
console.log(moveLen);
// 左右两边区域的总宽度 = 大容器宽度 - 中间区域拖拉框的宽度
let maxWidth = box.clientWidth - resize.offsetWidth;
// 限制左边区域的最小宽度为30px
if (moveLen < 30) moveLen = 30;
// 右边区域最小宽度为 150px 限制左边区域到150后不能再拉宽
if (moveLen > maxWidth - 150) moveLen = maxWidth - 150;
// 设置左边区域的宽度,通过换算为百分比的形式,实现窗体放大缩小自适应
console.log(moveLen / maxWidth * 100);
left.style.width =(moveLen / maxWidth * 100) + '%';
// 右边区域即是总大小 - 左边宽度 - 拖动条宽度
console.log(((maxWidth - moveLen) / maxWidth * 100));
mid.style.width = ((maxWidth - moveLen) / maxWidth * 100)+ '%';
};
// 鼠标松开事件
document.onmouseup = function (evt) {
document.onmousemove = null;
document.onmouseup = null;
resize.releaseCapture && resize.releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
};
resize.setCapture && resize.setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
return false;
};
</script>
</body>
</html>
1
https://gitee.com/yzishan/webs.git
git@gitee.com:yzishan/webs.git
yzishan
webs
webs
master

搜索帮助