直接看代码吧
<html>
<head>
<title>拖动调整左右两侧div的宽度</title>
<style>
#container {
display: flex;
height: 400px;
width: 100%;
}
#left,
#right {
/* flex: 1; */
width: 50%;
}
#left {
background-color: #ff0000;
}
#right {
background-color: #00ff00;
}
#handle {
position: absolute;
top: 0;
width: 5px;
height: 100%;
background-color: #0000ff;
cursor: col-resize;
}
</style>
</head>
<body>
<div id="container">
<div id="left"></div>
<div id="right"></div>
</div>
</body>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
var container = $("#container");
var left = $("#left");
var right = $("#right");
var handle = $("<div id='handle'></div>");
var width = $(window).width();
// 添加拖动句柄
container.append(handle);
// 设置拖动句柄的初始位置
handle.css("left", left.outerWidth());
// 绑定拖动事件
handle.on("mousedown", function(e) {
e.preventDefault();
console.log("research=== 111")
// 记录鼠标初始位置和左侧div的宽度
var startX = e.pageX;
var initialLeftWidth = left.outerWidth();
// 绑定鼠标移动事件
$(document).on("mousemove", function(e) {
e.preventDefault();
// 计算鼠标移动距离
var moveX = e.pageX - startX;
console.log("mousemove width:", width)
console.log("mousemove left:", left)
console.log("mousemove moveX:", moveX)
console.log("mousemove initialLeftWidth:", initialLeftWidth)
// 更新左侧div和拖动句柄的宽度
left.width(initialLeftWidth + moveX);
right.width(width-initialLeftWidth- moveX);
left.css('width', initialLeftWidth + moveX)
handle.css("left", left.outerWidth());
});
// 绑定鼠标释放事件
$(document).on("mouseup", function() {
$(document).off("mousemove");
$(document).off("mouseup");
});
});
});
</script>
</html>