Core > マウスによる要素の移動

マウスドラッグでDOM要素を移動する。

HTML

<div id="foo" draggable="true">Move</div>

CSS

#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;
}

JavaScript

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) {
     // クリックのターゲットが自分かどうかを確認
        if ( e == this.panel ){
            // 自分自身なら、ドラッグを許可
            this.drag = true;

        } else {
            // 自分でなければ、ドラッグを不許可
            this.drag = false;
        }
    }


    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.w / 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 = 0;
                panel.style.position = 'absolute';
                //panel.style.top = y + 'px';
                panel.style.left = x + 'px';
           // }
       // }
    }

    mousemove.init();

}());