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

  function moveObjset(obj){
    var moveObj = obj;

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

    var point = moveObj.getBoundingClientRect();
    var w1 = 0;
    var h1 = 0;
    var x = 0;
    var y = 0;
    var width = 0;
    var height = 0;
    var gomibakoRect;

    moveObj.ondragstart = function(e){
      return false;
    }

    function onMouseMove(event){
      event.preventDefault();// タッチによる画面スクロールを止める
      x = event.clientX;
      y = event.clientY;
      
      moveObj.style.left = (x - width) + "px"; //位置(左右)が変化
      moveObj.style.top = (y - height) + "px"; //位置(上下)が変化
      gomibakoRect = gomibako.getBoundingClientRect();
      if((x-width>=gomibakoRect.left-width && x-width<=(gomibakoRect.left+gomibakoRect.width-width)) && (y-height>=gomibakoRect.top-height && y-height<=(gomibakoRect.top+gomibakoRect.height-height))){
        gomibako.style.backgroundColor = "pink";
      }
      else{
        gomibako.style.backgroundColor = "white";
      }
    }

    moveObj.onmousedown = function(event){
      event.preventDefault();// タッチによる画面スクロールを止める
      console.log(moveObj + "にマウスがくっついた");
      x = event.clientX;
      y = event.clientY;
      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 + "からマウスが離れた");
      if((x-width>=gomibakoRect.left-width && x-width<=(gomibakoRect.left+gomibakoRect.width-width)) && (y-height>=gomibakoRect.top-height && y-height<=(gomibakoRect.top+gomibakoRect.height-height))){
        gomibako.style.backgroundColor = "white";
        moveObj.classList.add('hidden');
        gomibakoget++;
        console.log(gomibakoget);
        if(gomibakoget >= 7){
          var gomibakosuc = document.querySelector(".popup-success");
          gomibakosuc.classList.remove('hidden');
        }
      }
      document.removeEventListener("mousemove",onMouseMove);
    }
  }
}
draganddrop();