简体   繁体   中英

jQuery Drag and Drop - How to add image into variable

I'm trying to implement a simple drag and drop game that allows you to match the image to the correct body part.

With help from an open source so far I've been able to implement numbers and text, however instead of the numbers '1, 2, 3, 4, 5, 6" I want these to be images in the box, that will then be draggable to the text.

Below is the variable that is used to create the numbers, I'm wondering how I would change the numbers to images?

var numbers = [ 1, 2, 3, 4, 5, 6 ];
numbers.sort( function() { return Math.random() - .5 } );

for ( var i=0; i<6; i++ ) {
$('<div>' + numbers[i] + '</div>').data( 'number', numbers[i] ).attr( 'id',       'card'+numbers[i] ).appendTo( '#cardPile' ).draggable( {
  containment: '#content',
  stack: '#cardPile div',
  cursor: 'move',
  revert: true
} );
}

I've also attached a Live Link to allow you to better understand.

Thanks

var numbers = [ 1, 2, 3, 4, 5, 6 ];
var imgs = [ '/images/1.gif','/images/2.gif','/images/3.gif','/images/4.gif','/images/5.gif','/images/6.gif' ];

numbers.sort( function() { return Math.random() - .5 } );

for ( var i=0; i<6; i++ ) {
$('<div><img  src="' + imgs[numbers[i] - 1] + '" alt="alt"/></div>').data( 'number', numbers[i] ).attr( 'id',         
   'card'+numbers[i] ).appendTo( '#cardPile' ).draggable( {
  containment: '#content',
  stack: '#cardPile div',
  cursor: 'move',
  revert: true
 } );
}

There are obvious ways to get around using an array of imgs but this was just an example.

I think you can just set the css background image property for all divs

    var numbers = [ 1, 2, 3, 4, 5, 6 ];
    numbers.sort( function() { return Math.random() - .5 } );

    for ( var i=0; i<6; i++ ) {
      $('<div></div>').data( 'number', numbers[i] )
           .attr( 'id','card'+numbers[i] )
           .appendTo( '#cardPile' )
           .draggable({
             containment: '#content',
             stack: '#cardPile div',
             cursor: 'move',
             revert: true
           })
           .css('background-image', 'url(' + numbers[i] + '.png)');
    }

You need to have 1.png, 2.png, 3.png, 4.png, 5.png in the same folder .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM