我也使用交互,所以我知道你的意思。我会尽力帮助你。
因此,您需要存储每个交互对象,例如在普通对象中
function dragMoveListener(event) {
var target = event.target;
// keep the dragged position in the data-x/data-y attributes
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
var products = {
apple: interact("#apple" /* your own selector, name */).draggable({
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
// enable autoScroll
autoScroll: true,
listeners: {
// call this function on every dragmove event
move: dragMoveListener,
}
}),
banana: interact("#banana").draggable({
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
// enable autoScroll
autoScroll: true,
listeners: {
// call this function on every dragmove event
move: dragMoveListener,
}
}),
carrrot: interact("#carrot").draggable({
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
// enable autoScroll
autoScroll: true,
listeners: {
// call this function on every dragmove event
move: dragMoveListener,
}
})
};
function getProductPosition(name) {
const interactNode = products[name].context(); // returns the node
return [interactNode.getAttribute("data-x"), interactNode.getAttribute("data-y")]
}
getProductionPosition("banana")
如您所见,interact(...).draggable(...) 返回对象(名为 Interactable),该对象具有方法 context(),返回类型为 Node。上下文方法会返回节点,所以我们可以存储为变量,比如:
const banana = interact("#banana").draggable({
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
// enable autoScroll
autoScroll: true,
listeners: {
// call this function on every dragmove event
move: dragMoveListener,
}
});
function getPosition(interactObject) {
const interactNode = interactObject.context(); // returns the node
return [interactNode.getAttribute("data-x"), interactNode.getAttribute("data-y")]
}
getPositionBanana() // => [x, y]
有关context() 的文档,请参阅https://interactjs.io/docs/api/Interactable.html#context