我爲我的webapp使用了一個自定義的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;
哪有我解決這個問題?
正如我寫的保證金可能會有所不同,是不是有一種方式,該空間不會影響可拖動項目的位置? – Lindow
@Lindow所以設置一個變量'var marginLeft = document.getElementById(「someId」)。offsetLeft;'然後代替+ 90其+ marginLeft – Bruce