jQuery UI how to set draggable containment option on parent's parent

寵の児 提交于 2019-12-12 07:26:05

问题


The jQuery UI Draggable interaction has a nice property for setting the containment as the parent.

$( ".selector" ).draggable({ containment: 'parent' });

I wish to set the containment as the parent's parent. There is no string value to accomplish this, as string the options are

'parent', 'document', 'window', [x1, y1, x2, y2]

I could calculate x1,y1,x2,y2 of the parent's parent at page load and use those values to set boundaries for a container relative to the document. But the container position can change relative to the parent's parent position if the window is resized after page load. The native 'parent' option keeps the draggable element within the parent element regardless of window resizing.

Is there a way to accomplish this draggable containment using the parent's parent? .


回答1:


As per the documentation, the containment option can also be a jquery selector or an actual element. So you can do this:

$('.selector').draggable({
    containment: $('.selector').parent().parent()
});

Or even better yet:

$('.selector').each(function(){
    $(this).draggable({
        containment: $(this).parent().parent()
    });
});



回答2:


According to the docs, you do not have to pass in a string for the containment property. You can pass in any of:

Selector, Element, String, Array

So, just select the parent's parent with jQuery (i.e. $( ".selector" ).parent().parent()), and pass in instead of 'parent'.




回答3:


This works fine as well:

$('.selector').draggable({
    containment: "#parent",
    scroll: false
});



回答4:


If i use $(this).parent() my element go over the parent element.

$('.selector').draggable({
  containment: $(this).parent()
});

But with parent it works fine.

$('.selector').draggable({
  containment: "parent"
});


来源:https://stackoverflow.com/questions/8084793/jquery-ui-how-to-set-draggable-containment-option-on-parents-parent

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