js拖拽实现方式
js拖拽
方式一:drag、drop
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> div{ width: 200px; height: 80px; border: 1px solid #ccc; } </style> <body> <span id="span" draggable="true" ondragstart="drag(event)">拽我啊</span> <div class="div1" ondragover="dragover()" ondrop="drop(event)"></div> <div class="div2" ondragover="dragover()" ondrop="drop(event)"></div> </body> <script> //实现拖拽 function drag(event){ event.dataTransfer.setData("span",event.target.id) } function dragover(){ event.preventDefault() } function drop(event){ event.preventDefault() var data = event.dataTransfer.getData("span") event.target.appendChild(document.getElementById(data)) } </script> </html>
方式二:mousedown
、mousemove
、mouseup
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <style type="text/css"> body{ margin: 0; padding: 0; } .d1,.d2{ width:100px; height: 100px; top: 10px; left: 10px; background-color: deepskyblue; position: absolute; } .d2{ top: 10px; left: 150px; background-color: aquamarine; } </style> <body> <div class="d1"></div> <div class="d2"></div> </body> </html> <script type="text/javascript"> let d1 = document.querySelector(".d1"); let d2 = document.querySelector(".d2"); class Dra{ constructor(ele) { this.ele = ele } downFn(){ this.ele.onmousedown = e=>{ let x,y let ev = e || window.event; console.log(ev.clientX,ev.clientY) x = ev.clientX - this.ele.offsetLeft; y = ev.clientY - this.ele.offsetTop; this.moveFn(x,y) } } moveFn(x,y){ this.ele.onmousemove = e=>{ let ev = e || window.event let xx = e.clientX let yy = e.clientY this.setStyle(xx-x,yy-y) this.upFn() } } setStyle(x,y){ this.ele.style.left = x+"px" this.ele.style.top = y+"px" } upFn(){ this.ele.onmouseup= () =>{ this.ele.onmousemove = "" } } } let dra = new Dra(d1) dra.downFn() let dra2 = new Dra(d2) dra2.downFn() class Limit extends Dra{ constructor(ele) { super(ele) } setStyle(x,y){ x = x<0?0:x y = y<0?0:y super.setStyle(x,y) } } let limit = new Limit(d2) limit.downFn()</script>