Simple JavaScript drag and drop witout the help of a library

后端 未结 4 862
我寻月下人不归
我寻月下人不归 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:38

    While I agree that library is the way to go, the answer you want is onmousedown, onmousemove, onmouseup. You have to handle those three events.

    In onmousedown you'd find the target (event.target or similar in different browsers) and set draggedObject = event.target. You'd also start handling the onmousemove event.

    Whenever the onmousemove event fired, you'd move the dragged element based on the difference in position since last time the onmousemove event fired.

    In the onmouseup event, you'd clear your draggedObject variable and stop handling onmousemove.

    It's not very crossbrowser, but it's the core of what you'd need to do for dragging and dropping.

提交回复
热议问题