检查droppable是否包含正确的可拖动?

时间:2017-02-06 07:24:50

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

我正在为大学制作一个简单的迪士尼游戏。游戏的目标是有3个迪士尼角色,有6个名字。玩家必须将正确的名称拖动到3个字符,然后单击“提交”并移至下一级别。

如何在单击按钮时验证字符图片上是否有正确的名称(可拖动)(可放置)

这是我的代码

<div id="characters">
      <div id="character1"><img src="images/Goofy.png"></div>
      <div id="character2"><img src="images/Mickey_Mouse.png"></div>
      <div id="character3"><img src="images/snow_white.png"></div>
</div>

<div id="options">
     <div id="option1" class="option">Goofy</div>
     <div id="option2" class="option">Snow White</div>
     <div id="option3" class="option">Figaro</div>
     <div id="option4" class="option">Pete</div>
     <div id="option5" class="option">Mickey Mouse</div>
     <div id="option6" class="option">Donald Duck</div>
</div>
<button onclick="init()">Play Again</button>

Jquery的:

$('#option1').draggable({
     containment: '#content',
     cursor: 'move',
     snap: '#content',
     revert: 'invalid',

 });

$("#character1, #character2, #character3").droppable({
    drop:dropmade,
    over: overMe,
    out: normal,
}) 
 });   

function dropmade(event, ui) {
   ui.draggable.draggable( 'disable' );
    alert('You have made a drop')
    $(this).droppable("destroy");

}

function overMe(event, ui) {
    $('#character1').css('background-color', 'green')
}

function normal(event, ui) {
    $('#character1').css('background-color', 'transparent ')
}

function init(event, ui ) {
var option = $("#character1");
var answer = ui.draggable.data('#option1')

if (option == answer) {
    alert("Hello")
}

}

1 个答案:

答案 0 :(得分:0)

您可以在调用drop函数时添加一个类(在您的情况下为'dropmade'),然后在提交时检查该元素是否具有此类。像这样:

function checkDropped(){
  if($( "#droppable" ).hasClass("ui-state-highlight")){
    alert("yes");
  }else alert("no");
}
$( function() {
    $( "#draggable" ).draggable();
    $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" )
          .find( "p" )
            .html( "Dropped!" );
      }
    });
  } );
#draggable { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }
#droppable { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<input type="button" id="check" onClick="checkDropped()" value="Submit"/>
</br>
<div id="draggable" class="ui-widget-content">
  <p>Drag me to my target</p>
</div>
 
<div id="droppable" class="ui-widget-header">
  <p>Drop here</p>
</div>