如何使用jquery将一个div拖动到另一个div?

时间:2014-11-03 07:03:21

标签: jquery html

我正在尝试使用jquery使用拖放来匹配以下小游戏。首先我尝试使用下面的代码将droggable元素移动到掉落的地方(Div),

CSS

#wrapper {
    width: 500px;
    border: 1px solid black;
    overflow: hidden; /* will contain if #first is longer than #second */
}
#first {
    width: 250px;
    float:left; /* add this */
    border: 1px solid red;
}
#second {
    border: 1px solid green;
    overflow: hidden; /* if you don't want #second to wrap below #first */
}

的index.jsp

<div align="center">
<div align="center" id="wrapper">
<div id="Questions">

<label id="Q1">Cat</label><br><br>
<label id="Q2">Cow</label><br><br>
<label id="Q3">Eagle</label><br><br>
</div>

<div id="Answers">

<label id="A1">Milk</label><br><br>
<label id="A2">Snake</label><br><br>
<label id="A3">Rat</label><br><br>
</div>

</div>
</div>



 <script type="text/javascript">


     $(function(){



$("#A1").draggable({
    revert: "invalid",
    snap: "#Questions"
    stack: "#A1",

    drop: function( event, ui ) {

         //here want to get draggable's id and droped element's id.
         // if(ui.draggable' id =='Q1' && DropedElemnts's id =='A1'){ alert("Matched") }

      }
});
$("#A2").draggable({
    revert: "invalid"
    snap: "#Questions"
    stack: "#A2"
});
$("#A3").draggable({
    revert: "invalid"
    snap: "#Questions"
    stack: "#A3"
});


});




</script>

当我将Answer div的元素拖到Question div上时,它会消失。如何解决这个问题?

我正在尝试的是,如果我拖动并放在 Cat 上,则意味着它应该说匹配。

如何获取拖动元素id值和删除元素id值?

1 个答案:

答案 0 :(得分:2)

这是一个工作小提琴:http://jsfiddle.net/39khs/1003/

$(".draggable").draggable({ cursor: "crosshair", revert: "invalid"});
 $("#A3").droppable({ accept: ".draggable", 
       drop: function(event, ui) {
           var draggable = ui.draggable;
           if($( this ).text() == "Rat" && draggable.text() == "Cat" ){
           alert("Matched");
           }
                console.log($( this ).text() +"----" +draggable.text());
               $(this).removeClass("border").removeClass("over");
         var dropped = ui.draggable;
        var droppedOn = $(this);
        $(dropped).detach().css({top: 0,left: 0}).appendTo(droppedOn);      
            }, 
      over: function(event, elem) {
              $(this).addClass("over");
               console.log(this.id);
      }
            ,
              out: function(event, elem) {
                $(this).removeClass("over");
              }
                 });
 $("#drop").sortable();

 $("#origin").droppable({ accept: ".draggable", drop: function(event, ui) {
                console.log("drop");
               $(this).removeClass("border").removeClass("over");
         var dropped = ui.draggable;
        var droppedOn = $(this);
        $(dropped).detach().css({top: 0,left: 0}).appendTo(droppedOn);      


            }});

希望这会对你有所帮助。