简体   繁体   中英

Jquery UI: Set draggable element's drop position

When dropping a draggable item implemented with jQuery UI, is there a way to define which part of the draggable item is used to determine the drop target position/element?

Eg I am moving a 100x100 div in a table formed of 100x25 cells. Right now, the target cell seems to be determined by the center of the helper div. I would like the target cell to be the one at the top of the div.
This is a calendar view where the table's columns are days and rows are times. The div represents an event, and it can vary in height depending on the length of the event. It is important that when dragging an event around, the user knows where it will drop so that the time is right. Currently, if the user drops a 2-hour event so that the top is at 08:00, the target cell will end up being the one at 09:00.
I could make the visual helper element smaller while it's being dragged to help with the targeting, but I would prefer to keep it full-sized.

Visual aid (black boxes representing events):
视觉辅助

My current implementation:

$(this).draggable({snap: 'td.dropTd', snapTolerance: "10"})

EDIT: Here is a code example. The console prints the cell that the element is dropped to. https://jsfiddle.net/akrzpvb2/2/

Consider the following code.

Example: https://jsfiddle.net/Twisty/r8h0asL3/4/

JavaScript

$(function() {
  for (var i = 1; i < 11; i++) {
    $('tbody').append('<tr><td id="a-' + i + '""></td><td  id="b-' + i + '""></td></tr>');
  }

  $('.dragDiv').draggable({
    containment: $("tbody"),
    snap: 'td',
    snapMode: 'inner',
    snapTolerance: "15"
  });
  $('tbody td').droppable({
    accept: '.dragDiv',
    drop: function(event, ui) {
      ui.draggable.css({
        top: "",
        left: ""
      }).appendTo(this);
    }
  });
});

You can see here that the snap methods you tried were on the right path. I added containment so that the User can't drag it out of the schedule.

For drop , we need to remove the position styling and then append it to the drop target.

Moving forward, you might consider floating the DIV over the table. This way it can "cover" the time frames versus being an element inside a cell.

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