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

前端 未结 8 710
孤独总比滥情好
孤独总比滥情好 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:22

    1. To bring the div on top of other elements you have to assign it a high z-index. Additionally, you can set box-shadow to give a feedback to the user that the element is draggable.
    2. You have to listen for a total of three events: mousedown, mouseup, and mousemove. On mousedown you have to attach a listener on mousemove, which tracks the mouse pointer movements and moves the div accordingly, and on mouseup you have to remove the listener on mousemove.
    3. Moving the div with the mouse is a bit tricky. If you translate the div to the pointer's position, the pointer will always point to the top left corner of the div, even when you click at the bottom right corner. For this, you have to calculate the coordinate difference between the div (top left corner) and the mouse pointer, in the mousedown event handler. Then, you have to subtract that difference from the mouse position before translating the div to that position, in the mousemove event handler.

    See the demo for a better idea.

    
    
      
        
        
        
        Document
        
      
      
        

提交回复
热议问题