javascript - 如何为可拖动元素添加底部和右侧约束?
问题描述
我有一个函数,允许将任何元素拖到新位置并成为父 div 的左上界。我对如何将相同的逻辑应用于父 div 的底部和右侧边界感到困惑。我搜索过的其他 stackoverflow 问题并没有解决我的问题。
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;
}
}
解决方案
推荐阅读
- ios - WKWebView 不使用 URLCache
- c++ - 将数字附加到枚举以获取其他枚举
- javascript - 如何使用 Vanilla JS 通过检查和 clearInterval() 来触发 setInterval() 取消选中复选框?
- java - 使用 XWPFDocument 打开 docx 文件时出现 NullPointerException
- python-3.x - 我想为部署在 heroku 上的 python 烧瓶应用程序记录一些用户操作。建议我做这件事的方法
- jenkins - 卷曲命令传递脚本行以获取 crumb 值并执行我的 groovy 脚本
- c# - 忽略 ASP.NET Web API 中的控制器
- github - 什么是 github 中未经身份验证和经过身份验证的请求?
- mysql - 关于mysql参数max_connections的问题
- php - 使用 MSSQL 选项安装 LimeSurvery 4.2