我有一个jQuery UI对话框,当用户单击按钮时会打开该对话框,我希望对话框出现在按钮附近。这并不难,例如:
var pos = $('#mybutton').offset();
$('#mydlg').dialog({
// ...
autoOpen: false,
position: [pos.left, pos.top]
});
问题是当按钮位于屏幕的最右侧或屏幕的最底部时。新打开的对话框将导致窗口滚动,因为它会离开屏幕。
如何计算位置,以便对话框向左/向上打开,以便仅在这些情况下保持在屏幕上?
答案 0 :(得分:2)
var pos = $('#mybutton').offset();
//if dialog height/width are known
var dialogTop = pos.Top;
var dialogLeft = pos.left;
if((dialogHeight + pos.top) > $(window).height())
{
dialogTop -= dialogHeight;
}
if((dialogWidth + pos.left) > $(window).width())
{
dialogLeft -= dialogWidth;
}
$('#mydlg').dialog({
autoOpen: false,
position: [dialogLeft, dialogTop]
});
//if the dialog height/width are unknown then move this to a function in the dialog onLoad