2013-10-30 48 views
1

假設我們在一個頁面中有多個可拖動的元素和多個可放置的目標。每個可拖動元素只有一個可放置目標。我的問題是:如何測試正確的元素是否被放在正確的目標上。 下面是一個例子小提琴:http://jsfiddle.net/D25Rt/爲可拖動的對象設置條件時 - jquery - UI

這是從示例代碼:

$("#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的新手,有人能給我一些關於如何以及應該在哪裏做的提示嗎?在接受選項或在下降選項?

+0

您需要使用'draggable'的'stop'方法。請閱讀更多信息:http://api.jqueryui.com/draggable/#event-stop – ahren

回答

1

拖放事件被激怒only when accepted draggable is dropped on droppable,所以我會首先重新考慮使用接受選項 - 您可以傳遞返回true/false作爲參數的函數。

但是!通過接受函數被調用頁面上的所有可拖動的元素,因此創建類似:

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/

希望它可以幫助莫名其妙。