拖拽(Drag and Drop)是指用户可以通过鼠标或其他输入设备将界面上的元素从一个位置移动到另一个位置。可改变大小(Resizable)则允许用户调整元素的尺寸。这两个功能在现代Web应用中非常常见,尤其是在图形编辑器、布局工具和仪表板等场景中。
mousedown
、mousemove
和mouseup
事件来实现拖拽和缩放。touchstart
、touchmove
和touchend
事件来实现。以下是一个简单的JavaScript示例,展示如何实现一个可拖拽且可改变大小的矩形元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Resize</title>
<style>
#resizable {
width: 200px;
height: 200px;
background-color: #f0f0f0;
position: absolute;
top: 50px;
left: 50px;
border: 1px solid #ccc;
}
.handle {
width: 10px;
height: 10px;
background-color: #007bff;
position: absolute;
bottom: 0;
right: 0;
cursor: nwse-resize;
}
</style>
</head>
<body>
<div id="resizable">
<div class="handle"></div>
</div>
<script>
const resizable = document.getElementById('resizable');
const handle = document.querySelector('.handle');
let isDragging = false;
let startX, startY, startWidth, startHeight;
resizable.addEventListener('mousedown', (e) => {
if (e.target === handle) {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(resizable).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(resizable).height, 10);
} else {
isDragging = true;
startX = e.clientX - resizable.offsetLeft;
startY = e.clientY - resizable.offsetTop;
}
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
if (e.target === handle) {
const width = startWidth + (e.clientX - startX);
const height = startHeight + (e.clientY - startY);
resizable.style.width = `${width}px`;
resizable.style.height = `${height}px`;
} else {
resizable.style.left = `${e.clientX - startX}px`;
resizable.style.top = `${e.clientY - startY}px`;
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
</script>
</body>
</html>
mousemove
事件中频繁修改样式导致的重绘和回流。transform
属性代替left
和top
,因为transform
不会触发重绘和回流。interact.js
)来处理跨浏览器兼容性问题。通过以上示例和解决方法,你可以实现一个基本的拖拽且可改变大小的元素。根据具体需求,可以进一步优化和扩展功能。
云+社区沙龙online [技术应变力]
DB TALK 技术分享会
云+社区沙龙online
云+社区技术沙龙[第7期]
云+社区技术沙龙[第5期]
云+社区技术沙龙[第28期]
云+社区技术沙龙[第27期]
云+社区技术沙龙[第12期]
领取专属 10元无门槛券
手把手带您无忧上云