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(); w1 = point.left + point.width; h1 = point.top + point.height; width = x - w1; height = y - h1; 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();