<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>可拖动调整高度的Div</title>
<style>
body {
font-family: Arial, sans-serif;
height: 2000px; /* 增加页面高度以显示滚动条 */
}
.container {
width: 300px;
border: 1px solid #ccc;
overflow: hidden;
position: relative;
margin: 50px auto; /* 居中容器 */
}
.resizable {
width: 100%;
background-color: #f0f0f0;
position: relative;
}
.resizer {
width: 100%;
height: 10px;
background-color: #007bff;
cursor: ns-resize;
position: absolute;
bottom: 0;
left: 0;
}
.section {
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="resizable section" id="section1">
<div class="content">小 div 1</div>
<div class="resizer"></div>
</div>
<div class="resizable section" id="section2">
<div class="content">小 div 2</div>
<div class="resizer"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var isResizing = false;
var currentSection;
// 绑定mousedown事件到每个resizer
$('.resizer').on('mousedown', function(e) {
isResizing = true;
currentSection = $(this).parent(); // 获取当前正在调整的section
e.preventDefault(); // 防止文本选择
});
// 绑定mousemove事件到document
$(document).on('mousemove', function(e) {
if (isResizing && currentSection) {
// 计算新的高度
var newHeight = e.pageY - currentSection.offset().top;
// 更新高度,设置最小高度
if (newHeight > 50) {
currentSection.css('height', newHeight + 'px');
}
}
});
// 绑定mouseup事件到document
$(document).on('mouseup', function() {
isResizing = false;
currentSection = null; // 重置当前section
});
});
</script>
</body>
</html>