我有一些代码可以拖动使用香草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考虑到元素的大小。