简体   繁体   中英

Javascript Draggable

I am trying to make a page where the user can drag and drop images anywhere on the screen: In my HTML file, the images have class = "draggable". I am not able to get the images to move to where it is dragged to. Below is my javascript code:

const draggables = document.querySelectorAll('.draggable');
console.log(draggables);

var isDown = false;

draggables.forEach((draggable) => {

  draggable.addEventListener('mousedown',function(e){
    isDown = true;
    offset = [
      draggable.offsetLeft - e.clientX,
      draggable.offsetTop  - e.clientY
    ];
    console.log("mousedown")
  }, true)

  document.addEventListener('mouseup', function(){
      isDown = false;
  }, true)

  document.addEventListener("mousemove",function(e){
    event.preventDefault();
    if(isDown){
      draggable.style.left = (e.clientX + offset[0]) + 'px';
      draggable.style.top = (e.clientY + offset[1] + 'px');
    }
  }, true)
});

FIXED Here is the code that works:

const draggables = document.querySelectorAll('.draggable');
console.log(draggables);

var isDown = false;
var current;

draggables.forEach((draggable) => {
  draggable.addEventListener('mousedown',function(e){
    isDown = true;
    offset = [
      draggable.offsetLeft - e.clientX,
      draggable.offsetTop  - e.clientY
    ];
    current = draggable;
    console.log("mousedown", offset)

  }, true)
});

  document.addEventListener('mouseup', function(){
      isDown = false;
      console.log("mouseup")
  }, true)

  document.addEventListener("mousemove",function(e){
    event.preventDefault();
    console.log("mousemove")
    if(isDown){
      current.style.left = (e.clientX + offset[0]) + 'px';
      current.style.top = (e.clientY + offset[1] + 'px');
    }

  }, true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM