diff --git a/demos/targetDrag.html b/demos/targetDrag.html new file mode 100644 index 0000000..e694f53 --- /dev/null +++ b/demos/targetDrag.html @@ -0,0 +1,40 @@ + + + + + + TargetDrag + + + +
+ 点击拖拽 +
+ + + + + + + + diff --git a/lib/dom/index.js b/lib/dom/index.js index 3b41ae5..08e55d1 100644 --- a/lib/dom/index.js +++ b/lib/dom/index.js @@ -115,4 +115,5 @@ let dom = { element.dispatchEvent(event) return this }, + } diff --git a/lib/targetDrag/index.js b/lib/targetDrag/index.js new file mode 100644 index 0000000..3376f53 --- /dev/null +++ b/lib/targetDrag/index.js @@ -0,0 +1,48 @@ +class TargetDrag{ + constructor(options) { + let defaultOptions={ + mouseDownX:'', + mouseDownY:'', + initX:'', + initY:'', + flag:false + } + this.options=Object.assign({},defaultOptions,options); + this.checkOptions().bindEvents() + } + + checkOptions() { + if (!this.options.element) { + throw new Error('element is required') + } + return this + } + + bindEvents(){ + let targetElement=this.options.element; + + this.options.element.addEventListener('mousedown',(e)=>{ + this.options.mouseDownX=e.pageX||e.clientX; + this.options.mouseDownY=e.pageY||e.clientY; + this.options.initX=this.options.element.offsetLeft; + this.options.initY=this.options.element.offsetTop; + this.options.flag=true; + }) + + this.options.element.addEventListener('mousemove',(e)=>{ + console.log(this.options.flag); + if (this.options.flag) { + let mouseMoveX=e.clientX,mouseMoveY=e.clientY; + targetElement.style.left=parseInt(e.clientX)-parseInt(this.options.mouseDownX)+parseInt(this.options.initX)+'px'; + targetElement.style.top=parseInt(e.clientY)-parseInt(this.options.mouseDownY)+parseInt(this.options.initY)+'px'; + } + }) + + this.options.element.addEventListener('mouseup',(e)=>{ + this.options.flag=false; + }) + + return this; + } + +}