0

高さと幅が固定された一連のボタンがあり、それらは親div内のどこにでもドラッグおよびドロップできる必要があります。

クライアントのリクエストによると、私は外部ライブラリを使用できません.まあ... jQueryで数秒でこれを行うことができましたが、これはその欠点の1つであると思います.より基本的なことを学ぶことができません...

どうすればそれを行うことができますか?これに関する問題は、これらのボタンがドラッグ可能な div 内にあるため、配置に注意する必要があることです。おそらく相対しか使用できません。

どうすればそれを行うことができますか?前もって感謝します。

4

1 に答える 1

0

Peter-Paul Kochは、ドラッグ アンド ドロップに関する優れたハウツーを書いています。私は自分で書いている途中でこの 3/4 しか覚えていなかったので、それをフィドルでまとめました

function makeDraggable(draggable, container){
    // In case you don't want to have a container
    var container = container || window;
    // So we know what to do on mouseup:
    // At this point we're not sure the user wants to drag
    var dragging  = false;

        // The movement listener and position modifier
        function dragHandler(moveEvent){
            moveEvent.preventDefault();

            dragging        = true;

            // Ascertain where the mouse is
            var coordinates = [
                    moveEvent.clientX,
                    moveEvent.clientY
            ];

            // Style properties we need to apply to the element 
            var styleValues = {
                    position : 'absolute',
                    left     : coordinates[0] + 'px',
                    top      : coordinates[1] + 'px'
            };

            // Apply said styles
            for(property in styleValues){
                    if(styleValues.hasOwnProperty(property)){
                            draggable.style[property] = styleValues[property];
                    }
            }
    }

    function dropHandler(upEvent){
        // Only interfere if we've had a drag event
        if(dragging === true){
            // We don't want the button click event to fire!
            upEvent.preventDefault();

            // We don't want to listen for drag and drop until this is clicked again
            container.removeEventListener('mousemove', dragHandler, false);
            draggable.removeEventListener('mouseup',   dropHandler, false);

            dragging = false;
        }
    }

    // Where all the fun happens
    draggable.addEventListener('mousedown', function dragListener(downEvent){
        downEvent.preventDefault();

        // The drag event
        container.addEventListener('mousemove', dragHandler, false);

        // The end of drag, if dragging occurred
        draggable.addEventListener('mouseup',   dropHandler, false);
    }, false);
}​ 
于 2012-12-18T12:23:09.380 に答える