Jquery draggable constrain using drag function

2019-06-02 07:09发布

问题:

I need to use jQuery draggable in quite a complicated geometrical shape, and it is not possible to calculate the frame beforehand.

So, containment option isn't cut for solving this problem.

I've been thinking about drag function, checking my condition and returning false to prevent dragging. But, the problem is, that after returning false from drag function for the first time, dragging process stops, as if user have released the mouse button.

Any suggestions on preventing dragging out of the shape without canceling dragging process?

回答1:

I have solved similar issue with resizable. I had to manually set sizes though. Try something like that:

yourdraggable.bind( 'drag', function() {

  var left = $(this).css('left'),
      top = $(this).css('top'),
      width = $(this).width(), 
      height= $(this).height();

  //determine if dragging should contain or continue

  //if contain 
  $(this).css( { left: containLeft, top: containTop } );

});

You could analyze left and top separately but you got the idea



回答2:

The main trick is to set the position of the ui helper object within the drag event function.

Example

Here I assume you've a function to calculate the Y limit based on the X position.

$(x).draggable({
    drag: function (e, ui) {
        ui.position.top = limitY(ui.position.left);
    }
});

Here is a jsFiddle that I created while trying to solve a similar problem myself.