JavaScript拖放代理

时间:2010-06-30 01:45:00

标签: javascript jquery drag-and-drop draggable

我想在我的Web应用程序上启用拖放行为。我有一个想要拖动的图像。图像位于另一个具有透明部分的图像后面,以便您可以看到它下面的图像。我不想改变图像的顺序。我的想法是我应该在两个透明的图像上使用另一个图层,并将其用作代理,将事件传输到我想要拖动的图像。 jQuery UI的draggable函数不允许我实时传输事件,即只有在完成拖动时我才能挂钩它正在做的事情。

是否有JavaScript库或jQuery插件允许我对元素进行拖放并让它们实时将这些事件传输到另一个元素?

1 个答案:

答案 0 :(得分:2)

也许我不明白你想要完成什么,但你应该能够毫不费力地拖放重叠的图像(demo)。

只需将两个图像包装在div中,然后使div可拖动:

CSS(无需使.dragme位置相对,因为它是在可拖动脚本中完成的)

.dragme img {
 position: absolute;
 top: 0;
 left: 0;
}

HTML

<div class="dragme">
 <img src="image1.gif">
 <img src="image2.gif">
</div>

脚本

$(".dragme").draggable();

我更新the demo,这不太漂亮,可能有更好的方法,但基本上这会在框架上放置一个不可见的叠加层,然后在拖动叠加层时定位图像。

CSS

#draggable, #droppable {
 width: 450px;
 height: 250px;
 padding: 0.5em;
 margin: 10px;
 background: #ddd;
 color:#000;
}
.dragme {
 position: relative;
 width: 100px;
 padding: 5px;
}
.dragme img {
 position: absolute;
 top: 55px;
 left: 30px;
}
.demo {
 width: 500px;
}
.border {
 position: absolute;
 top: 75px;
 left: 30px;
 z-index: 1;
}

HTML

<div class="demo">
 <div class="border">
  <img src="http://www.imageuploading.net/image/thumbs/large/border-564.png">
 </div>
 <div id="draggable" class="ui-widget-content">
  <p>Drag from here</p>   
  <div class="dragme">
   <img src="http://i142.photobucket.com/albums/r117/SaltyDonut/Icons/evilpuppy.gif">
  </div>
 </div>
 <div id="droppable">
  <p>Drop here</p>
 </div>
</div>

脚本(该演示使用$(document).ready,因为jsFiddle不喜欢$(window).load)

$(window).load(function(){
 // cycle through draggable divs (in case there are more than one)
 $(".dragme").each(function(){
  var img = $(this).find('img');
  var pos = img.position();
  // create div overlay on image
  $('<div/>', {
   class : 'overlay',
   css: {
    position: 'relative',
    top: pos.top,
    left: pos.left,
    width: img.outerWidth(),
    height: img.outerHeight(),
    zIndex: 100
   }
  })
   // save original image position
   .data('pos', [pos.left, pos.top])
   .appendTo($(this));

  // make overlay draggable
  $(this).find('.overlay').draggable({
   containment : '.demo',
   revert: true,
   revertDuration: 0,
   handle: 'div',
   // drag overlay and image
   drag: function(e,ui){
    img = $(this).parent().find('img');
    img.css({
     top: ui.position.top,
     left: ui.position.left
    });
   },
   // make image revert
   stop: function(e,ui){
    pos = $(this).data('pos');
    $(this).parent().find('img').animate({left: pos[0], top: pos[1] },500);
   }
  });
 });

 $("#droppable").droppable({
  drop : function(e,ui) {
   // append entire div wrapper (.dragme)
   ui.helper.parent().appendTo($(this));
  }
 });
});