Javascript 如何向可拖动元素添加底部和右侧约束?
我有一个函数,可以将任何元素拖到新位置,并将其左上方绑定到父div。我不知道如何将相同的逻辑应用于将底部和右上方绑定到父div。我搜索的其他stackoverflow问题没有解决我的问题Javascript 如何向可拖动元素添加底部和右侧约束?,javascript,Javascript,我有一个函数,可以将任何元素拖到新位置,并将其左上方绑定到父div。我不知道如何将相同的逻辑应用于将底部和右上方绑定到父div。我搜索的其他stackoverflow问题没有解决我的问题 function dragElement(element) { let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementById(element.id + "-header")) {
function dragElement(element) {
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(element.id + "-header")) {
// if present, the header is where you move the DIV from:
document.getElementById(element.id + "-header").onmousedown = dragMouseDown;
} else {
// otherwise, move the DIV from anywhere inside the DIV:
element.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
// 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.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
const rect = document.querySelector("#viewDiv").getBoundingClientRect();
const minLeft = rect.left;
const minTop = rect.top;
const maxRight = rect.right;
const maxBottom = rect.bottom;
let calcTop = element.offsetTop - pos2;
let calcLeft = element.offsetLeft - pos1;
// set the element's new position
// use the rectangular boundaries of the viewDiv and the element's offsets as constraints
element.style.left = Math.min(Math.max(minLeft, calcLeft), maxRight) + "px";
element.style.top = Math.min(Math.max(minTop, calcTop), maxBottom) + "px";
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}