<div class="demo">
<div id="droparea" class="droppable"></div>
<div id="box"></div>
</div>
.demo{
background-color: #f0f0f0;
box-sizing: border-box;
border: 1px solid #646464;
padding: 10px;
width: 100%;
height: 300px;
position: relative;
}
#droparea {
background-color: #e6e6e6;
box-sizing: border-box;
border: 1px dotted #646464;
width: 50%;
height: 100%;
}
#box {
cursor: grab;
background-color: #000;
width: 40px;
height: 40px;
position: absolute;
top: 50%;
left: 70%;
}
let dropJudge = null;
const boxDOM = document.querySelector('#box');
const dropareaDOM = document.querySelector('#droparea');
boxDOM.onmousedown = function(event) {
boxDOM.style.cursor = 'grabbing';
let shiftX = event.clientX - boxDOM.getBoundingClientRect().left;
let shiftY = event.clientY - boxDOM.getBoundingClientRect().top;
boxDOM.style.position = 'absolute';
boxDOM.style.zIndex = 1000;
movePosition(event.pageX, event.pageY);
// #box要素の位置を決める
function movePosition(pageX, pageY) {
boxDOM.style.left = pageX - shiftX + 'px';
boxDOM.style.top = pageY - shiftY + 'px';
}
// マウスを動かした時の処理
function mouseMove(event) {
movePosition(event.pageX, event.pageY);
boxDOM.hidden = true;
let elemBelow = document.elementFromPoint(event.clientX, event.clientY);
boxDOM.hidden = false;
let droppableBelow = elemBelow.closest('#droparea');
if (dropJudge != droppableBelow) {
if (dropJudge) {
notDroppable(dropJudge);
}
dropJudge = droppableBelow;
if (dropJudge) {
onDroppable(dropJudge);
}
}
}
document.addEventListener('mousemove', mouseMove);
// マウスを離した時にmousemoveイベントを解除する
document.onmouseup = function() {
document.removeEventListener('mousemove', mouseMove);
boxDOM.style.cursor = 'grab';
};
};
function onDroppable(element) {
element.style.background = '#969696';
}
function notDroppable(element) {
element.style.background = '#e6e6e6';
}
boxDOM.ondragstart = function() {
return false;
};
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.