【问题标题】:Set conditions for draggable objects when dropped - Jquery - UI设置拖放时可拖动对象的条件 - Jquery - UI
【发布时间】:2013-10-30 15:13:52
【问题描述】:

假设我们在一页中有多个可拖动元素和多个可放置目标。每个可拖动元素只有一个可放置目标。我的问题是:如何测试是否将正确的元素放在正确的目标上。 这是一个示例小提琴:http://jsfiddle.net/D25Rt/

这是示例中的代码:

$("#draggable-red, #draggable-blue, #draggable-green").draggable({ revert: "invalid", containment: "#content"});

$("#droppable-red").droppable({
    accept: "#draggable-red",
    activeClass: "ui-state-hover",
    hoverClass: "ui-state-active",
    drop: function(event, ui) {
        $(this).addClass("ui-state-highlight").find("p").html("Touch down!");
    }
});

$("#droppable-blue").droppable({
    accept: "#draggable-blue",
    activeClass: "ui-state-hover",
    hoverClass: "ui-state-active",
    drop: function(event, ui) {
        $(this).addClass("ui-state-highlight").find("p").html("Touch down!");
    }
});

$("#droppable-green").droppable({
    accept: "#draggable-green",
    activeClass: "ui-state-hover",
    hoverClass: "ui-state-active",
    drop: function(event, ui) {
        $(this).addClass("ui-state-highlight").find("p").html("Touch down!");
    }
});

更具体地说,关于前面的示例,如果我将蓝色球拖到红色框上,当我释放蓝色球时,我想显示一个警报(类似于“错误框...”)。我是 jQuery UI 的新手,有人可以给我一些关于我应该如何以及在哪里做的提示吗?在 accept 选项中还是在 drop 选项中?

【问题讨论】:

标签: jquery jquery-ui draggable droppable


【解决方案1】:

Drop 事件被触发only when accepted draggable is dropped on droppable,所以我会首先重新考虑使用接受选项 - 您可以传递返回 true/false 作为参数的函数。

但是!为页面上的所有可拖动元素调用传递给 accept 的函数,因此创建如下内容:

    accept: function(){
        if($(".ui-draggable-dragging").is("#draggable-red"))
            return true;
        else
            alert("I only accept red ball!");
    },

Causes multiple alerts even if you just try to move other draggable ball.

这样的事情应该没问题:

drop: function(event, ui) {
    if(ui.draggable.is("#draggable-red")){
        $(this).addClass("ui-state-highlight").find("p").html("Touch down!");
    }
    else{
        alert("I accept only red balls!");
        ui.draggable.draggable('option','revert',true);
    }
}

但它必须接受所有元素,所以它会破坏你的亮点。

JS 小提琴:http://jsfiddle.net/bFj68/1/

希望能有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 2017-04-18
    相关资源
    最近更新 更多