是否可以将包含(限制在另一个元素的边界内)添加到jQuery UI的Dialog?
答案 0 :(得分:10)
@ Mottie在正确的轨道上,但有一个更简单,更好的解决方案:
var container = $('.dialog-container'),
dialog = $('.ui-dialog');
dialog.draggable( "option", "containment", container );
与Mottie的解决方案不同,如果视口调整大小,这不会中断。我已经分叉了JSFiddle here。
答案 1 :(得分:3)
您可以定位对话框并对其应用包含。试试这个:
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] );
编辑:我为您设置了a demo Edit2:更改为使用对话框outerWidth& outerHeight
答案 2 :(得分:3)
@ Mac's正确,但解决方案尚未完成。您必须还设置对话框的Resizable小部件的包含。如果你只设置了Draggable,你会在拖动时获得遏制,但是当你抓住边缘并调整大小时,你仍然会超出范围。
所以你要做到这一点,假设#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'
之间切换相应窗口小部件的限制。然后尝试通过标题栏拖动对话框,和通过其边缘调整大小。请注意当您只选择“限制拖动”时会发生什么:
// 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;
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<div>Example</div>
<div id="area"></div>
<div id="win" title="test">
<label><input type="checkbox" id="draggable">Contain drag</label>
<label><input type="checkbox" id="resizable">Contain resize</label>
</div>
</body>