问题:write a complete example of a webpage with two columns. there is a middle bar between the two columns. It can be dragged to adjust the size of columns.
回答:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
/* Basic styling for the columns */
.row {
display: flex;
}
.column {
flex: 1;
padding: 20px;
border: 1px solid #ddd;
}
/* Draggable middle bar */
.middle-bar {
width: 6px;
cursor: col-resize;
background-color: #aaa;
}
</style>
</head>
<body>
<div class="row">
<div class="column" id="left-column">
<!-- Content for the left column -->
<h2>Left Column</h2>
<p>This is the left column content.</p>
</div>
<div class="middle-bar" id="middle-bar"></div>
<div class="column" id="right-column">
<!-- Content for the right column -->
<h2>Right Column</h2>
<p>This is the right column content.</p>
</div>
</div>
<script>
// JavaScript to make the middle bar draggable
const middleBar = document.getElementById('middle-bar');
const leftColumn = document.getElementById('left-column');
const rightColumn = document.getElementById('right-column');
let isDragging = false;
middleBar.addEventListener('mousedown', (e) => {
isDragging = true;
document.body.style.cursor = 'col-resize';
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const mouseX = e.clientX;
const leftColumnWidth = mouseX - leftColumn.getBoundingClientRect().left;
leftColumn.style.flex = `${leftColumnWidth}px`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
document.body.style.cursor = 'auto';
});
</script>
</body>
</html>
结果
可以拖动。但是有点怪。稍微修改两处后看起来不错。[1]
const leftColumnWidth = mouseX - leftColumn.getBoundingClientRect().left - 45;
leftColumn.style.flex = `0 0 ${leftColumnWidth}px`;