マウスドラッグにDOM要素の移動のメモ。
<div id="foo" draggable="true">Move</div>
#foo { width: 150px; height: 150px; margin: 20px; color: #CCC; background: #EFEFEF; border: 3px dotted #DDD; font-size: 2em; font-weight: 900; text-align: center; line-height: 150px; }
var mousemove = {};
(function() {
var panel = document.getElementById(‘foo’);
drag = false;
function init() {
document.addEventListener(‘mousedown’, mouseDown, false);
document.addEventListener(‘mouseup’, mouseUp, false);
document.addEventListener(‘mousemove’, mouseMove, false);
}
mousemove.init = init;
function mouseDown(e) {
drag = true;
}
function mouseUp() {
drag = false;
}
function mouseMove(e) {
if (drag == true) {
move(e);
}
}
function move(e) {
var offsetX, offsetY, x, y, rect = {};
rect.x = panel.offsetLeft;
rect.y = panel.offsetTop;
rect.w = panel.clientWidth;
rect.h = panel.clientHeight;
offsetX = rect.w / 2;
offsetY = rect.h / 2;
if (e.pageX > rect.x && e.pageX < rect.x + rect.w) {
if (e.pageY > rect.y && e.pageY < rect.y + rect.h) {
x = e.pageX - offsetX;
y = e.pageY - offsetY;
panel.style.position = 'absolute';
panel.style.top = y + 'px';
panel.style.left = x + 'px';
}
}
}
mousemove.init();
}());
[/javascript]
No comments yet.
改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。