最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I get a draggable to revert to the original position only if it was dragged onto an invalid droppable? - Sta

programmeradmin1浏览0评论

I have an element I want to allow to be dragged anywhere. However, if it is dropped onto a droppable which refuses it (via accept) I want it to revert to the original position before the drag. How can I acplish this?

EDIT: to be more specific: I want two conditions to be met in order for the item to be moved back: 1. It was dropped on a droppable and 2. The droppable didnt accept said item. Draggable's revert option only checks condition 2.

I have an element I want to allow to be dragged anywhere. However, if it is dropped onto a droppable which refuses it (via accept) I want it to revert to the original position before the drag. How can I acplish this?

EDIT: to be more specific: I want two conditions to be met in order for the item to be moved back: 1. It was dropped on a droppable and 2. The droppable didnt accept said item. Draggable's revert option only checks condition 2.

Share Improve this question edited Nov 29, 2011 at 16:47 chacham15 asked Nov 29, 2011 at 16:23 chacham15chacham15 14.3k26 gold badges121 silver badges218 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

I have some code which I think should work. Note that it doesn't use the accept option to specify which draggables the droppables will accept. Instead, you'll have to check whether or not a draggable should be rejected manually, in the drop event.

$(document).ready(function() {
    $('.droppable-class').droppable({
        drop: function(event, ui) {
            // check whether or not draggable should be rejected here...
            if (...) {
                ui.draggable.data('rejected', true);
            }
        }
    });

    $('.draggable-class').draggable({
        revert: false,
        start: function(event, ui) {
            ui.helper.data('rejected', false);
            ui.helper.data('original-position', ui.helper.offset());
        },
        stop: function(event, ui) {
            if (ui.helper.data('rejected') === true) {
                ui.helper.offset(ui.helper.data('original-position'));
            }
        }
     });

You want to use sortable dude - something like:

    $('#sortable-area').sortable({
    accept: '.child',
    items: '.child',
    revert: 300,
    opacity: 0.8,
    containment: 'document'
});

This should automatically snap the element back if it isn't far enough to replace one of the other elements. You just put this on the container

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论