JavaScript 面向对象的拖拽
Posted hyshi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 面向对象的拖拽相关的知识,希望对你有一定的参考价值。
一、body
<div id="box"></div>
二、css
<style>
#box {
position: abaolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
}
</style>
三、javascript
<script>
class Drag{
constructor(el) {
this.el = el;
el.startOffset = null;
el.startPoint = null;
let move = (e) => {
this.move(e);
}
let end = (e)=>{
document.removeEventListener(‘mousemove‘, move);
document.removeEventListener(‘mouseup‘, end);
}
el.addEventListener(‘mousedown‘, (e)=>{
this.start(e);
document.addEventListener(‘mousemove‘, move);
document.addEventListener(‘mouseup‘, end);
})
}
start(e) {
let {el} = this;
this.startOffset = {
x: el.offsetLeft,
y: el.offsetTop
}
this.startPoint = {
x: e.clientX,
y: e.clientY
}
}
move(e) {
let {el, startOffset, startPoint} = this;
let nowPoint = {
x: e.clientX,
y: e.clientY
}
let dis = {
x: nowPoint.x - startPoint.x,
y: nowPoint.y - startPoint.y
}
el.style.left = startOffset.x + dis.x + ‘px‘;
el.style.top =startOffset.y + dis.y + ‘px‘;
}
}
let box = document.querySelector(‘#box‘);
let drag = new Drag(box);
</script>
以上是关于JavaScript 面向对象的拖拽的主要内容,如果未能解决你的问题,请参考以下文章