【发布时间】:2018-01-04 14:51:39
【问题描述】:
我通过使用与 w3Schools 中的示例大致相同的代码制作了一个可拖动元素:
//Make the DIV element draggagle:
dragElement(document.getElementById(("mydiv")));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
// 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;
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
问题是我需要将元素限制在视口内加上一点填充。 我有一些解决方案,您只需检查元素位置是否小于 0,是否将其设置回 0,或者是否大于宽度/高度,将其设置为宽度/高度。这还不够好,因为它会产生一种我不想要的抖动反弹效果。
所以我想知道这个问题是否有更明显的解决方案?也不使用 jQuery。
【问题讨论】:
-
当我在这里的 sn-p 或小提琴中尝试时,示例不起作用(div 实际上不可拖动 - 控制台中没有错误)
-
谢谢,考虑添加样式或链接到问题本身。我只能给你一个提示,但我没有完整的解决方案。您可以在移动 div 之前测试值:
if(elmnt.offsetLeft - pos1 >= 0){ elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; },此示例可防止在左侧出现。但是你会注意到,它会导致文本被选中,我还没有解决这个问题..
标签: javascript html css drag