window.onload = function () {
const box = elt('div', null, 'JavaScript');
document.body.appendChild(box);
let boxOffsetX, boxOffsetY;
box.style.display = 'inline-block';
box.style.position = 'absolute';
box.style.padding = '10px';
box.style.backgroundColor = 'blue';
box.style.color = 'white';
box.style.cursor = 'pointer';
box.addEventListener('mousedown', function mouseDownListener(e) {
document.addEventListener('mousemove', mouseMoveListener, false);
boxOffsetX = e.offsetX; boxOffsetY = e.offsetY;
}, false);
document.addEventListener('mouseup', function mouseUpListener(e) {
document.removeEventListener('mousemove', mouseMoveListener, false);
}, false);
function mouseMoveListener(e) {
box.style.left = e.pageX - boxOffsetX + 'px';
box.style.top = e.pageY - boxOffsetY + 'px';
}
};
function elt(name, attributes) {
const node = document.createElement(name);
if (attributes) {
for (let attr in attributes) {
if (attributes.hasOwnProperty(attr)) {
node.setAttribute(attr, attributes[attr]);
}
}
}
for (let i = 2; i < arguments.length; i++) {
let child = arguments[i];
if (typeof child == 'string') {
child = document.createTextNode(child);
}
node.appendChild(child);
}
return node;
}
JS-ドラッグ・アンド・ドロップ
----------------
A [Pen](https://codepen.io/taquaki/pen/MOqNaN) by [Takaaki Sato](https://codepen.io/taquaki) on [CodePen](https://codepen.io).
[License](https://codepen.io/taquaki/pen/MOqNaN/license).