问题描述
我正在开发一个小型网络应用程序,用户可以在其中将 <div>
拖动到容器 <div>
内的不同位置。容器限制了目标 <div>
可以拖动到的位置。
这是我的代码,目前有效。
function catchTarget(e) {
this.style.left = this.offsetLeft + "px";
this.style.top = this.offsetTop + "px";
this.style.zIndex="1000";
// caculate the offset of the mouseclick relative to the object
var dX = e.pageX - this.offsetLeft;
var dY = e.pageY - this.offsetTop;
// calculate the bounding rectangle of the container
var cw = this.clientWidth;
var ch = this.clientHeight;
var container = document.getElementById('container');
var x1 = container.offsetLeft;
var y1 = container.offsetTop;
var x2 = x1 + container.clientWidth;
var y2 = y1 + container.clientHeight;
// move the element around within its bounding rectangle
this.onmousemove = function (e) {
let pageX = e.pageX;
let pageY = e.pageY;
if ( pageX > (x1 + dX) && pageX < (x2 - cw + dX) && pageY > (y1 + dY) && pageY < (y2 - ch + dY) ) {
this.style.left = (e.pageX - dX) + "px";
this.style.top = (e.pageY - dY) + "px";
}
}
// re-calculate the bounding rectangle of the container after window scroll
window.onscroll = function() {
x1 = container.offsetLeft + window.pageXOffset;
y1 = container.offsetTop + window.pageYOffset;
x2 = x1 + container.clientWidth;
y2 = y1 + container.clientHeight;
}
// release the DOM element
this.onmouseup = function () {
this.style.zIndex="500";
this.onmousemove = null;
}
}
window.onload = function () {
const object1 = document.getElementById("dragTarget1");
object1.onmousedown = catchTarget;
const object2 = document.getElementById("dragTarget2");
object2.onmousedown = catchTarget;
}
然而,当我将鼠标移动得太快时,我会“失去”目标并且它不再移动,除非我将鼠标移回它上面然后它会一直保持直到我再次单击鼠标左键。可以在 here 中找到工作示例。
我的问题是:当鼠标移动太快时,如何避免丢失目标?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)