0

我有一系列固定高度和宽度的按钮,这些按钮需要在父 div 内的任何位置可拖放。

根据客户的要求,我不能使用任何外部库,嗯……我本可以在几秒钟内用 jQuery 完成这项工作,但我想这是它的缺点之一:你无法学习更多基本的东西……

我该怎么做呢?这样做的一个问题是这些按钮在一个也可拖动的 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 回答