拖拽组件编程可以通过多种方式实现,包括原生JavaScript、Vue.js、React等。下面我将分别用JavaScript和Vue.js给出两个示例。
原生JavaScript实现拖拽组件
```javascript
// Drag.js
class Drag {
constructor(config) {
this.moveTarget = document.getElementById(config.id);
this.startLeft = parseInt(this.moveTarget.style.left) || 0;
this.startTop = parseInt(this.moveTarget.style.top) || 0;
this.startClientX = this.startLeft;
this.startClientY = this.startTop;
this.MAX_LEFT = config.maxLeft || document.documentElement.clientWidth - this.moveTarget.offsetWidth;
}
ready() {
this.moveTarget.style.position = 'absolute';
document.addEventListener('mousedown', this.handleMouseDown.bind(this));
}
handleMouseDown(event) {
if (event.target !== this.moveTarget) return;
this.isDragging = true;
const rect = this.moveTarget.getBoundingClientRect();
this.dragStartX = event.clientX - rect.left;
this.dragStartY = event.clientY - rect.top;
document.addEventListener('mousemove', this.handleMouseMove.bind(this));
document.addEventListener('mouseup', this.handleMouseUp.bind(this));
}
handleMouseMove(event) {
if (!this.isDragging) return;
const newLeft = event.clientX - this.dragStartX;
const newTop = event.clientY - this.dragStartY;
if (newLeft < 0) newLeft = 0;
if (newTop < 0) newTop = 0;
if (newLeft > this.MAX_LEFT) newLeft = this.MAX_LEFT;
this.moveTarget.style.left = newLeft + 'px';
this.moveTarget.style.top = newTop + 'px';
}
handleMouseUp() {
this.isDragging = false;
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
}
}
// 使用方法
var d = new Drag({ id: 'dragPannel', maxLeft: 500, maxTop: 200 });
d.ready();
```
Vue.js实现拖拽组件