拖放到特定区域

时间:2016-12-03 19:27:53

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

我试图创建一个游戏,用户必须按特定顺序放置每张卡。我可以将名称拖放到可丢弃区域,但我如何能够将特定卡分配给特定插槽。

这是我的js代码:

var correctCards = 0;
$( init );

function init() {

  // Hide the success message
  $('#successMessage').hide();
  $('#successMessage').css( {
    left: '580px',
    top: '250px',
    width: 0,
    height: 0
  } );

  // Reset the game
  correctCards = 0;
  $('#cardPile').html( '' );
  $('#cardSlots').html( '' );

  // Create the pile of shuffled cards

  var cards = ["Aiba", "Ninomiya", "Ohno", "Sakurai", "Matsumoto"];
  cards.sort( function() { return Math.random() - .5 } );

  for ( var i=0; i<cards.length; i++ ) {
    $('<div>' + cards[i] + '</div>').data('img',i ).appendTo( '#cardPile' ).draggable( {
      containment: '#content',
      stack: '#cardPile div',
      cursor: 'move',
      revert: true
    } );
  }


  // Create the card slots
  var slots = [ ' ', ' ', ' ', ' ', ' '];
  for ( var i=1; i<=slots.length; i++ ) {
    $('<div>' + slots[i-1] + '</div>').data( 'number', i ).appendTo(     '#cardSlots' ).droppable( {
      accept: '#cardPile div',
      hoverClass: 'hovered',
      drop: handleCardDrop
    } );
  }

}

function handleCardDrop( event, ui ) {
  var slotNumber = $(this).data( 'name' );
  var cardNumber = ui.draggable.data( 'name' );

  // If the card was dropped to the correct slot,
  // change the card colour, position it directly
  // on top of the slot, and prevent it being dragged
  // again

  if ( slotNumber == cardNumber ) {
    ui.draggable.addClass( 'correct' );
    ui.draggable.draggable( 'disable' );
    $(this).droppable( 'disable' );
    ui.draggable.position( { of: $(this), my: 'left top', at: 'left top'     } );
    ui.draggable.draggable( 'option', 'revert', false );
    correctCards++;
  } 

  // If all the cards have been placed correctly then display a message
  // and reset the cards for another go

  if ( correctCards == 10 ) {
    $('#successMessage').show();
    $('#successMessage').animate( {
      left: '380px',
      top: '200px',
      width: '400px',
      height: '100px',
      opacity: 1
    } );
  }

}

0 个答案:

没有答案