demo

Dragging is one of the simplest actions interact. Js provides. To make an element dragable, you need to create an interactable on your target element, then call the draggable method and fill in the configuration you need.

<div class="draggable"> Draggable Element </div>
Copy the code
.draggable {
  touch-action: none;
  user-select: none;
}
Copy the code
const position = { x: 0.y: 0 }

interact('.draggable').draggable({
  listeners: {
    start (event) {
      console.log(event.type, event.target)
    },
    move (event) {
      position.x += event.dx
      position.y += event.dy

      event.target.style.transform =
        `translate(${position.x}px, ${position.y}px)`}}})Copy the code

In addition to the usual interaction event properties, dragmove events also provide

Drag event property describe
dragEnter The dropzone into which the object is dragged
dragLeave The dropzone from which the object is dragged

Remember to use CSS touch-action: None to prevent browser panning (scrolling) when the user drags by touch, and user-select: None to disable text selection.

lockAxisstartAxis

// Lock the starting direction of the drag
interact(singleAxisTarget).draggable({
  startAxis: 'xy'
  lockAxis: 'start'
});

// Start drag when the drag event starts horizontally
interact(horizontalTarget).draggable({
  startAxis: 'x'
  lockAxis: 'x'
});
Copy the code

There are two options for controlling the direction of the drag axis: startAxis and lockAxis.

StartAxis sets the direction of movement to the initial direction of movement. Use ‘x’ to start dragging horizontally and ‘y’ to set to start dragging vertically.

LockAxis to lock the direction of drag events. If ‘start’ is used, the drag is locked to the direction in which it started.