As a front end worker, there’s a good chance you’ve encountered a need to implement oneCan drag and dropWidgets, such as the feedback icon in the bottom right corner of the nuggets page.Ask the designer for an icon, but what about drag-and-drop effects? How do you do that? Easy Drag was created to solve this problem!

The principle of

First of all, we need to determine how to implement the drag effect. Here are two ways:

  • One is to use absolute positioning, adjust when draggingtopandleftValue, but this scenario depends on how the parent component is positioned
  • The other is usingtransform, displacement of elements based on their original positions

Here, of course, we should choose the latter, the most “safe and pollution-free” scheme.

implementation

The general scheme is determined, the specific implementation is the details, but there are still many points to pay attention to:

What if the element originally had a transform attribute?

The transform attribute must be superimposed on top of the element style’s transform, so window.getComputedStyle(element).transform is used. The transform property is then concatenated

How did the element go off course?

The reason is that when the transform attribute is concatenated, the dragged translate is concatenated to the original transform value, and the original ratate rotates the coordinate system of the element, resulting in “deflection” when the translation effect is applied.

This problem can be avoided by adding the translation effect to the original transform value.

The final result

The transform property causes the browser to create separate layers for the element, and changing the position of the element by transform only triggers the browser to recompose layers, not rearrange them, so it’s smooth

use

The installation

npm i easy-drag

use

import enableDrag from 'easy-drag';
const disableDrag = enableDrag(document.querySelector('.draggable'));
disableDrag();
Copy the code

function

  • Easy drag supports undrag
  • Easy-drag supports setting the drag range, which cannot be exceeded by defaultdocument.body
  • Easy drag supports setting drag points, using the following scenario: The popover needs to be set to drag, but only the title area
  • Easy-drag supports setting custom callbacks, includingonDragStart,onDrag,onDragEnd

Github

Easy – drag: github.com/junqiuzhang…

In the meantime, AMway takes a look at my other Github projects:

  • Github.com/junqiuzhang…
  • Github.com/junqiuzhang…
  • Github.com/junqiuzhang…