How to implement a drag-and-drop div from scratch with JavaScript?

前端 未结 8 709
孤独总比滥情好
孤独总比滥情好 2020-12-08 05:07

It should be a combination of CSS and JavaScript. The steps to do should be:

  1. Make it on top of all other elements (which property to specify?)
  2. Catch t
8条回答
  •  时光取名叫无心
    2020-12-08 05:19

    The standard Drag and Drop API is widely recognized to suck big hairy donkey balls. So I wouldn't recommend doing it from scratch. But since that's your question, there are one set of requirements for making something draggable, and one set of requirements for properly setting up a drop zone:

    Dragging:

    • The dom node must have the "draggable" property set to true

    Note: e.dataTransfer.setDragImage can be used to set an alternate drag image (the default is a transparent image of the dom node being dragged.

    Note2: e.dataTransfer.setData can be used inside the dragstart event to set some data that can be gotten back from the drop event.

    Dropping:

    • In the dragover event, e.preventDefault must be called
    • In the drop event, e.preventDefault must be called

    Example:

    
        
    Drag Me
    Drop Here

    However, there are a whole lot of gotchas in using this API, including that:

    • it takes a lot of work to distinguish between a dragmove event over a dropzone and a dragmove event related to a draggable item
    • dragmove fires even if your mouse isn't moving
    • dragleave and dragenter fire even if your mouse isn't moving in or out of the listening dom node (it fires whenever it crosses a child-parent bounary for some stupid reason)
    • And more..

    A better way

    I wrote a drag and drop library that makes it a ton easier to use the standard drag and drop API without all those gotchas. Check it out here:

    https://github.com/fresheneesz/drip-drop

提交回复
热议问题