【问题标题】:jQuery UI Drag and Drop more than oncejQuery UI 拖放不止一次
【发布时间】:2011-10-07 01:17:16
【问题描述】:

我目前正在编写一个脚本,该脚本允许用户将装饰图像拖到圣诞树上来装饰它。我正在使用 jquery-ui 使图像显示在可拖动到树上的侧栏中。它起作用了,有点。出于某种原因,在我将图像拖到树上后,您将无法再移动它,也无法在树上创建另一个可拖动对象,因为原始图像不再可拖动。

这是我想出的代码:

$(document).ready(function () {
$('[clickable]').click(function () {
    if ( $(this).attr('targets') )
    {
        $($(this).attr('targets')).css('background-image', 'url(' + $(this).attr('src') + ')');
    }
});

$('[draggable]').each(function () {
    $(this).css('z-index', '30');
    $(this).draggable({
    revert: \"invalid\"
    //, zIndex: 999
    , helper: 'clone'
     , containment: '#panel'
     , appendTo: '#' + $(this).attr('targets')
    });
});

$('[droppable]').each(function () {
    $(this).css('z-index', '-20');
    $(this).droppable({
        accept: '[targets=' + $(this).attr('id') + ']'
        , drop: function (e, ui) {
            $(this).append($(ui));
            $(ui).draggable({
                revert: \"invalid\"
                //, zIndex: 999
                 , containment: '#top'
                 , appendTo: '#top'//'#' + $(this).attr('targets')
                });
        }
    });
});
});

和html:

<div id="drop_area" droppable="droppable">
        <div id="canvas" droppable="droppable">
            <div id="background" droppable="droppable">
                <div id="tree" droppable="droppable">

                </div>
            </div>
        </div>

        <div id="selectors">
            <img src="./images/dressup/largepinkbow.png" draggable="draggable" targets="tree" />
        </div>

    </div>

【问题讨论】:

    标签: jquery jquery-ui drag-and-drop


    【解决方案1】:

    您以错误的方式处理其中一些问题。相反,如果使用 $.each 您可以在 jquery 选择上执行 .droppable 和 .draggable 。

    $('[draggable]').draggable({...})
    

    此外,您不应该在您放置的每个 ui 元素上重新实例化 .draggable() 插件。您所要做的就是为该元素定义一次,然后它在 dom 上的余生都可以拖动。

    类似:

    $('[draggable]')
    .css('z-index', '30')
    .draggable({
        revert: "invalid"
        //, zIndex: 999
        , helper: 'clone'
         , containment: '#panel'
         , appendTo: '[droppable]'
        });
    });
    
    $('[droppable]')
        .css('z-index', '-20');
        .droppable({
            accept: '[draggable]'
            , drop: function (e, ui) {
                $(this).append($(ui));
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 2021-07-21
      • 2012-03-18
      • 2017-04-18
      相关资源
      最近更新 更多