javascript - 防止元素被拖过屏幕的底部和右侧?
问题描述
我有一个函数可以使传递给它的任何元素都可以拖动。我已经成功地将元素从屏幕的左侧和顶部限制在elementDrag(e)
:
element.style.left = Math.min(Math.max(minLeft, calcLeft), maxRight) + "px";
element.style.top = Math.min(Math.max(minTop, calcTop), maxBottom) + "px";
但事实证明,为元素计算适当的右侧和底部位置很困难。如何防止元素被拖过屏幕的右侧和底部?这是代码:
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;
// get the boundaries of the parent div and the element's offsets
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";
}
解决方案
推荐阅读
- google-cloud-platform - 检索存储在 Secret Manager 中的 Google Cloud 中的环境变量
- javascript - TableCell Material UI 组件未识别的对象内容
- electron - webPreferences 中的“nativeWindowOpen”选项有什么用?
- c# - 注册表数据被存储多次,而不是在请求的地方
- ssl - Spring webclient 可以从 javax.net.ssl.truststore 导入证书吗?
- java - 可以使用 mvn surefire 插件在 Cucumber 并行测试中使用 ThreadLocal
- ruby-on-rails - 定制设计集成测试
- flutter - Flutter Futurebuilder 快照没有数据
- javascript - how to aggregate and do validation on array of object JavaScript?
- xsd - 限制元素接受布尔值(真/假)并在 xsd 内部映射到整数值