JavaScript How to Dynamically Move Div by Clicking and Dragging

前端 未结 6 1910
滥情空心
滥情空心 2020-12-23 14:06

Okay it would seem like it should be simple. I need to take an already existing div and move it according to mouse position within the window. I have searched everywhere and

6条回答
  •  星月不相逢
    2020-12-23 14:40

    Support for touch inputs

    All other answers (including the accepted one) do not work with touch inputs. Touch inputs have events different than that of mouse inputs. See Using Touch Events on MDN.

    The following code snippet works even with touch inputs. I have highlighted all lines of code that need to be added to support touch devices.
    The basic idea here is that every element containing draggable in the class list should be draggable. This concept is easier to follow when you have a big number of elements that need to be dragged.

    See this Glitch page and following for a demo.

    const d = document.getElementsByClassName("draggable");
    
    for (let i = 0; i < d.length; i++) {
      d[i].style.position = "relative";
    }
    
    function filter(e) {
      let target = e.target;
    
      if (!target.classList.contains("draggable")) {
        return;
      }
    
      target.moving = true;
      
    //NOTICE THIS 

提交回复
热议问题