我的小提琴目前有1个可拖动的项目
https://jsfiddle.net/wayneker/yfmh4kx6/4/
但我想总共添加71种不同形状的物品。我尝试添加<div id="draggable-element"></div>
,但我无法移动它。十字准线显示但不能移动它。我知道我将不得不为不同的形状添加不同的类,但我想我会首先尝试使用几个项目。我还需要了解可拖动物品的起始位置。
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;
答案 0 :(得分:2)
将draggable-element
设为class
,您可以将其应用于多个元素。此时,使用onmousedown
将getElementsByClassName()
函数绑定到类的所有元素。