我有一些用于拖动使用普通 JavaScript 的元素的代码,它工作正常,但我对如何将其限制为 t、l、r、b 或至少顶部和左侧感到摸不着头脑。请不要使用jquery。
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
elmnt.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// if (value = reached / exceeded){ stop dragging any
//further please}
elmnt.style.top = (topPos - pos2) + "px";
elmnt.style.left = (leftPos - pos1) + "px";
}
}
我可以计算出元素相对于其父元素的顶部(和左侧)位置,但似乎无法告诉它停止拖动。我在代码中添加了一个带注释的示例,我认为逻辑上应该是这样。但到目前为止,这意味着拖动完全停止,而不是我所追求的“约束”。任何帮助表示赞赏!
最佳答案
假设您有 calcLeft 和 calcTop 以及约束 minLeft、minTop、maxBottom 和 maxRight:
const left = Math.min(Math.max(minLeft, calcLeft), maxRight)
const top = Math.min(Math.max(minTop, calcTop), maxBottom)
然后分配这些值。
您所做的就是计算出计算位置的最大值和最小位置,这样您就不会低于该值,然后计算该结果的最小值和您的最大位置,这样您就不会高于该值那个。
确保您的 maxRight 和 maxBottom 考虑了元素的大小。
关于javascript - 如何向 javascript DragElement 添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469014/