Newer
Older
internship / js / drag-and-drop.js
@taka taka on 25 Mar 2022 2 KB drag-drop
function draganddrop(){
  var gomibako = document.getElementById("goul");
  gomibako.style.zIndex = "1";
  var moveObjs = document.querySelectorAll(".moveObj");
  for(obj of moveObjs){
    obj.addEventListener('click', moveObjset(obj), false);
    console.log(obj);
  }

  function moveObjset(obj){
    var moveObj = obj;

    moveObj.style.position = "absolute";
    moveObj.style.cursor = "pointer";
    moveObj.style.zIndex = "2";

    var w1 = moveObj.getBoundingClientRect().left; //画像がマウスの位置からズレるとマウスを離した時のイベントが機能しなかったため、ウィンドウのサイズからずれを修正
    var h1 = moveObj.getBoundingClientRect().top;
    moveObj.ondragstart = function(e){
      return false;
    }


    var width = 0;
    var height = 0;
    function onMouseMove(event){
      var x = event.clientX;
      var y = event.clientY;
      
      moveObj.style.left = (x - width) + "px"; //位置(左右)が変化
      moveObj.style.top = (y - height) + "px"; //位置(上下)が変化
      /*var gomibakoRect = gomibako.getBoundingClientRect();
      if((x>=gomibakoRect.left && x<=(gomibakoRect.left+gomibakoRect.width)) && (y>=gomibakoRect.top && y<=(gomibakoRect.top+gomibakoRect.height))){
        gomibako.style.backgroundColor = "pink";
      }
      else{
        gomibako.style.backgroundColor = "white";
      }*/
    }

    moveObj.onmousedown = function(event){
      console.log(moveObj + "にマウスがくっついた");
      var x = event.clientX;
      var y = event.clientY;
      var point = moveObj.getBoundingClientRect();
      width = x - point.left + (document.documentElement.clientWidth/20); //ポップアップ内の位置と画面全体の位置の差を計算
      height = y - point.top + (document.documentElement.clientHeight/20) + ((document.documentElement.clientHeight - document.documentElement.clientWidth)/20);
      console.log(x + ", " + y + ", " + point.left + ", " + point.top);
      document.addEventListener("mousemove",onMouseMove);
    }

    moveObj.onmouseup = function(event){
      console.log(moveObj + "からマウスが離れた");
      /*var x = event.clientX;
      var y = event.clientY;
      var width = moveObj.offsetWidth;
      var height = moveObj.offsetHeight;
      console.log(x + ", " + y + ", " + width + ", " + height);
      /*var gomibakoRect = gomibako.getBoundingClientRect();
      if((x>=gomibakoRect.left && x<=(gomibakoRect.left+gomibakoRect.width)) && (y>=gomibakoRect.top && y<=(gomibakoRect.top+gomibakoRect.height))){
        gomibako.style.backgroundColor = "white";
        moveObj.classList.add('hidden');
      }*/
      document.removeEventListener("mousemove",onMouseMove);
    }
  }
}
draganddrop();