Jquery draggable constrain using drag function

偶尔善良 提交于 2019-12-10 11:49:22

问题


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.



来源:https://stackoverflow.com/questions/7227656/jquery-draggable-constrain-using-drag-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!