How can I use jQuery to bind a fallen element inside a div?

I am trying to recreate the World of Warcraft action bar for training purposes.

So far I have a panel, and the individual slots are Droppable. What can I do when the yellow div falls inside the container, is it centered in the INIIDE.item div?

@{ ViewBag.Title = "Home Page"; } <script language="JavaScript"> $(function () { $(".draggable").draggable(); $(".item").droppable({ drop: function (event, ui) { $(this) .addClass("ui-state-highlight") .find("p") .html("Dropped!"); } }); }); </script> <div class="draggable"> </div> <div class="bar"> <div class="item"> <p>a</p> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> </div> 

alt text

+7
source share
1 answer

How about this:

 $(function() { $(".draggable").draggable(); $(".item").droppable({ drop: function(event, ui) { var $this = $(this); $this.append(ui.draggable); var width = $this.width(); var height = $this.height(); var cntrLeft = width / 2 - ui.draggable.width() / 2; var cntrTop = height / 2 - ui.draggable.height() / 2; ui.draggable.css({ left: cntrLeft + "px", top: cntrTop + "px" }); } }); }); 

Edit: I noticed that you have text in the target div . If you want this to work with other elements in droppable, you can place the moved element absolutely and offset it with the left and top parent:

 var width = $this.width(); var height = $this.height(); var top = $this.offset().top; var left = $this.offset().left; var cntrLeft = (width / 2 - ui.draggable.width() / 2) + left; var cntrTop = (height / 2 - ui.draggable.height() / 2) + top; 

and

 ui.draggable.css({ left: cntrLeft + "px", top: cntrTop + "px", zIndex:1, position: 'absolute' }); 

Notes:

  • ui.draggable is a draggable item that has been reset to droppable.
  • $this.append(ui.draggable) adds a dragged item to the droppable div , so positioning can be done exactly.

See a live example here: http://jsfiddle.net/andrewwhitaker/F3sD3/

+7
source

All Articles