我正在处理一个需要在整个页面上拖动图片的项目。我发现jQuery UI是一个非常有用的解决方案,它按预期工作,但遗憾的是我不能在项目中使用它。相反,我只需要使用纯JavaScript来完成它。通过一些谷歌搜索,我想出了这个:http://jsfiddle.net/tovic/Xcb8d/light/
这是完美的,它唯一的问题是它使用的是ID,这意味着我在页面上不能有多个可拖动的项目。我修改它以使用类:http://jsfiddle.net/Xcb8d/690/。代码的问题在于,即使两个元素都是可拖动的,一旦你开始拖动第二个元素,它的x_elem和y_elem就会关闭。这导致元素移动到鼠标的远方向。有谁知道是什么原因引起的?
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...
var draggables = document.getElementsByClassName('draggable-element');
for(i = 0; i < draggables.length; i++) {
draggables[i].onmousedown = function () {
_drag_init(this);
return false;
};
}
document.onmousemove = _move_elem;
document.onmouseup = _destroy;