```html <!DOCTYPE html> <html> <head> <style> /* 定义窗口的样式 */ .window { position: absolute; width: 400px; height: 300px; background-color: #f1f1f1; border: 1px solid #ccc; padding: 10px; } </style> </head> <body> <div id="myWindow" class="window"> <h2>可拖拽改变窗口大小的窗口</h2> <p>鼠标移动到窗口的边框上时,可以改变窗口的大小。</p> </div> <script> // 获取窗口元素 var windowElement = document.getElementById('myWindow'); // 定义边框大小改变的方向常量 var DIRECTIONS = { TOP: 'top', RIGHT: 'right', BOTTOM: 'bottom', LEFT: 'left' }; // 添加鼠标移动事件处理程序 windowElement.addEventListener('mousemove', handleWindowResize); function handleWindowResize(event) { var rect = windowElement.getBoundingClientRect(); var mouseX = event.clientX - rect.left; var mouseY = event.clientY - rect.top; // 判断鼠标在窗口的哪个边界上 var direction = getResizeDirection(mouseX, mouseY, rect.width, rect.height); // 设置鼠标样式 setCursorStyle(direction); // 添加边框大小改变的事件处理程序 windowElement.addEventListener('mousedown', function (e) { startResize(e, direction); }); } // 获取边框大小改变的方向 function getResizeDirection(mouseX, mouseY, width, height) { var borderSize = 8; // 边框大小 if (mouseY < borderSize) { return DIRECTIONS.TOP; } else if (mouseY > height - borderSize) { return DIRECTIONS.BOTTOM; } else if (mouseX < borderSize) { return DIRECTIONS.LEFT; } else if (mouseX > width - borderSize) { return DIRECTIONS.RIGHT; } else { return null; } } // 设置鼠标样式 function setCursorStyle(direction) { if (direction === DIRECTIONS.TOP || direction === DIRECTIONS.BOTTOM) { windowElement.style.cursor = 'ns-resize'; // 竖直方向的调整大小 } else if (direction === DIRECTIONS.LEFT || direction === DIRECTIONS.RIGHT) { windowElement.style.cursor = 'ew-resize'; // 水平方向的调整大小 } else { windowElement.style.cursor = 'default'; // 默认鼠标样式 } } // 开始边框大小改变操作 function startResize(event, direction) { event.preventDefault(); var startX = event.clientX; var startY = event.clientY; var startWidth = windowElement.offsetWidth; var startHeight = windowElement.offsetHeight; window.addEventListener('mousemove', resizeWindow); window.addEventListener('mouseup', function stopResize() { window.removeEventListener('mousemove', resizeWindow); window.removeEventListener('mouseup', stopResize); }); // 执行边框大小改变 function resizeWindow(event) { if (direction === DIRECTIONS.TOP) { var diffY = startY - event.clientY; windowElement.style.height = startHeight + diffY + 'px'; } else if (direction === DIRECTIONS.RIGHT) { var diffX = event.clientX - startX; windowElement.style.width = startWidth + diffX + 'px'; } else if (direction === DIRECTIONS.BOTTOM) { var diffY = event.clientY - startY; windowElement.style.height = startHeight + diffY + 'px'; } else if (direction === DIRECTIONS.LEFT) { var diffX = startX - event.clientX; windowElement.style.width = startWidth + diffX + 'px'; } } } </script> </body> </html> ```