简体   繁体   中英

Drag and drop script works only once but stops working [No jQuery]

I was making my own flexible javascript DnD script when I encountered an error. The div moves perfectly fine the first time, but the remaining times, it messes up the offset. I know what everyone is probably going to say; "why don't you use a library?" . The reason is because having my own personally designed script is easier to edit and understand. There is probably a more efficient way to do this, but here is the code:

 document.onmousemove = mouseCoords; var x = 0; var y = 0; var cl1= false; var time1= true; var divid; var offs1; var offs2; function mouseCoords(e) { x = ex y = ey if(cl1 === true){ document.getElementById(divid).style.top= y-offs1+"px"; document.getElementById(divid).style.left= x-offs2+"px"; } } var drag1 = function(i, cas) { divid= i if(time1=== true){ cl1= true time1= false }else{ cl1= false time1= true } switch(cas){ case 0: offs1 = 0; offs2 = 0; break; case 1: offs1 = y; offs2 = x; break; } } 
 <div id="1" onmousedown="drag1(1, 1);" onmouseup="drag1(1, 0);" style="background-color: yellow; width: 500px; height: 300px; position: fixed;"></div> 

The first time there are no hiccups, but all proceeding times, the offset isn't close enough to the mouse to function almost seamlessly. How do I make the script work like it does the first time, every time? (It doesn't show up as much in the snippet.)

I added considering current div coordinates. It seems to work more stably:

 document.onmousemove = mouseCoords; var x = 0; var y = 0; var cl1= false; var divid; var offs1; var offs2; var _top; var _left; function mouseCoords(e) { x = ex y = ey if(cl1 === true){ document.getElementById(divid).style.top = _top + (y-offs1) + 'px'; document.getElementById(divid).style.left = _left + (x-offs2) + 'px'; } } var drag1 = function(i, cas) { divid= i switch(cas){ case 0: offs1 = 0; offs2 = 0; cl1= false; break; case 1: var rect = document.getElementById(divid).getBoundingClientRect(); _left = rect.left; _top = rect.top; offs1 = y; offs2 = x; cl1= true; break; } } 
 <div id="1" onmousedown="drag1(1, 1);" onmouseup="drag1(1, 0);" style="background-color: yellow; width: 500px; height: 300px; position: fixed;"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM