Simple JavaScript drag and drop witout the help of a library

后端 未结 4 817
我寻月下人不归
我寻月下人不归 2021-02-09 07:13

I am simply looking for a way of using drag and drop without jquery or any other library. If a dragged object is dropped on another element the later element should start an eve

4条回答
  •  广开言路
    2021-02-09 07:27

    I agree with the other answers. A library will save you a lot of time and headache. This is coming from someone who just recently created a drag-and-drop control from scratch.

    If you insist though this is what you'll need to do:

    1. Bind a onmousedown event to the div you want to drag (div.onmousedown).
    2. Change the div's position style to absolute (div.style.position = 'absolute')
    3. Begin capturing mouse movement (document.onmousemove).
    4. On mouse move update the div's position (div.style.top|left = '[location]px')
    5. On the div's onmouseup event (or the document's) unbind all the handlers and do any other cleanup (null out position changes, etc).

    Some problems a library will probably solve:

    1. While dragging you will select text on the page (looks ugly).
    2. Binding to events is different between browsers.
    3. You have to calculate the size of the element being dragged if you want to show placeholders and to make it not "pop" when you begin dragging the control (since changing to absolute positioning will remove the element from flow).
    4. You will probably want your dragged element to move fluidly so you will have to store some mouse offset when selecting the element or automatically center the element to the mouse.
    5. If you want to drag an item in a list you'll have to write a ton more custom code for that list to accept the dragged item.
    6. You'll have to take into consideration dragging when the window is scrolled and possibly dragging inside other elements that are positioned strangely.

提交回复
热议问题