我的最终目标是拥有一个产品分类系统,所以我需要一种方法来获得移动对象的更新位置和标识符。如果能举个例子,我们将非常感谢。
发布于 2021-01-24 22:58:14
我也使用了interact,所以我知道你的意思。我试着帮你。
因此,您需要存储每个interact对象,例如存储在一个普通对象中
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(...)返回object (名为Interactable),该对象具有带有返回类型Node的方法context()。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
https://stackoverflow.com/questions/65868281
复制相似问题