将scr图像拖放到另一个scr图像

时间:2016-08-31 10:10:09

标签: javascript jquery

如何将图像1拖放到图像2

HTML

图片1

<img height="42" width="42" src="//swnaws.com/widget/v2/upload/x_141.png">

图片2

<span class="holder" style="background-image: url(&quot;//swnaws.com/wi/a_37.png&quot;);"></span>

我试过了

$("img[src*='x_141.png']").draggable.addClass("holder");

1 个答案:

答案 0 :(得分:1)

Ok, what you tried so far has no sense (you need more research), so you are too far away from your goal. But i'll guide you by a simple example and links to the documentation needed.

First, you need jQuery and jQuery UI (this last one has the draggable and droppable methods). You can find latest versions at Google CDN.

Once you have these requirements, see this easy example:

$(function(){

    // make the image draggable, use a clone if you want to maintain the original image
    $('img').draggable({ helper: 'clone' });

    // set up and control the droppable
    $('.holder').droppable({
        accept: 'img',
        drop: function(event, ui){ /* on drop, retrieve the image src and set it to the target's bg */
            var img_src = $(ui.helper).attr('src');
            $('.holder').css('background', 'red url(' + img_src + ') no-repeat center center');
        }
    });

});

Here's the live example, so you can begin from there: https://jsfiddle.net/re1xwsm3/.

Also, read calmly both jQuery UI Draggable Documentation and jQuery UI Droppable Documentation to understand correctly how it works.