我正在为我的 web 应用程序使用自定义 JavaScript 可拖动项,但它存在问题,我在名为 .container_elements
的 div 周围添加了一些空间,当可拖动项被移动时它消失了来自鼠标。
我需要将可拖动项保持在鼠标位置(.container_elements
周围的边距可能会有所不同,我不会也不会使用 JQuery 可拖动项)。
要重现该问题,只需拖动该框,您就会看到问题:https://jsfiddle.net/Lindow/Xcb8d/2194/
HTML :
<div style="margin-top:90px; margin-left:90px;">
<!--
adding spacement near the draggable product the issue,
(margin, padding, or even position absolute with top, left doesn't work)
-->
<div class="container_elements">
<div id="draggable-element">Drag me!</div>
</div>
</div>
JavaScript :
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
我该如何解决这个问题?
最佳答案
你的问题是 offsetLeft 和 offsetTop 不考虑 parent 的边距所以要解决你的问题要么设置
<div style="margin-top:90px; margin-left:90px;">
到
<div style="margin-top:0px; margin-left:0px;">
或在这里说明
x_elem = x_pos - selected.offsetLeft+90;
y_elem = y_pos - selected.offsetTop+90;
关于javascript - 为什么 div 附近的空间会影响拖动时可拖动元素的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44188956/