简体   繁体   English

拖放脚本只能运行一次,但会停止运行[No jQuery]

[英]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. 遇到错误时,我正在制作自己的灵活javascript DnD脚本。 The div moves perfectly fine the first time, but the remaining times, it messes up the offset. div第一次移动非常好,但是其余时间会弄乱偏移量。 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. 第一次没有打h,但是在所有处理过程中,偏移距离鼠标都不够近,几乎无法无缝运行。 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. 我添加了考虑当前div坐标。 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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