如何在jQuery UI对话框上设置包含?

是否有可能将包含(限制在另一个元素的边界)添加到jQuery UI的Dialog ?

您可以定位对话框并对其应用包含。 试试这个:

var container = $('.dialog-container'), dialog = $('.ui-dialog'); // get container top left corner locations var cx1 = container.offset().left, cy1 = container.offset().top; // get dialog size var dw = dialog.outerWidth(), dh = dialog.outerHeight(); // get container bottom right location, then subtract the dialog size var cx2 = container.width() + cx1 - dw, cy2 = container.height() + cy1 - dh; dialog.draggable( "option", "containment", [cx1, cy1, cx2, cy2] ); 

编辑:我为你设置了一个演示 。
Edit2:更改为使用对话框outerWidth&outerHeight

@ Mottie在正确的轨道上,但有一个更简单,更好的解决方案:

 var container = $('.dialog-container'), dialog = $('.ui-dialog'); dialog.draggable( "option", "containment", container ); 

与Mottie的解决方案不同,如果视口resize,这不会中断。 我在这里分叉了JSFiddle。

@Mac是在正确的轨道上,但解决方案并不完整。 您还必须设置对话框的Resizable小部件的包含。 如果你只设置了Draggable,你会在拖动时获得遏制,但当你抓住边缘并resize时,你仍然会超出范围。

所以你要做到这一点,假设#mydialog是你最初创建对话框的元素,而#boundary是你想要限制它的元素(顺便说一句,容器参数也可以是一个选择器):

 let ui = $('#mydialog').closest('.ui-dialog'); // get parent frame ui.draggable('option', 'containment', '#boundary'); // <-- drag, but not resize ui.resizable('option', 'containment', '#boundary'); // <-- don't forget!!! 

这是一个示例代码段,切换复选框以在'document' (默认值)和'#area'之间切换相应窗口小部件的限制。 然后尝试通过标题栏拖动对话框, 通过其边缘resize。 请注意当您只选择“限制拖动”时会发生什么:

 // Create dialog from #win with mostly default options. $('#win').dialog({ width: 200, height: 150, position: { my: 'center', at: 'center', of: '#area' } }); // When checkbox changed, update confinement settings. $('#draggable, #resizable').change(function () { let d = $('#draggable').prop('checked'); let r = $('#resizable').prop('checked'); let ui = $('#win').closest('.ui-dialog'); ui.draggable('option', 'containment', d ? '#area' : 'document'); ui.resizable('option', 'containment', r ? '#area' : 'document'); }); 
 #area { position: relative; left: 2ex; top: 2ex; width: 400px; height: 300px; border: 1px solid red; } #win { font-size: 10pt; display: flex; flex-direction: column; } label { display: flex; align-items: center; } 
       
Example
Interesting Posts