http://jqueryui.com/demos/position/
jQuery UI Position实用程序检测正在定位的元素何时溢出窗口并使用“collision”选项自动将其放置在窗口内。
当元素溢出特定的div而不是整个窗口时,是否可以这样做?
谢谢。
答案 0 :(得分:3)
是的,使用using属性。
$('#somediv').position({
my: 'right top',
at: 'left top',
of: $('#someotherdiv'),
using: function(pos) {
// Figure out the bounds of the position that will be set
var x1 = pos.left;
var x2 = pos.left + $(this).width();
var y1 = pos.top;
var y2 = pos.top + $(this).height();
// Figure out the bounds of the div we want to make sure we are inside
var bpos = $('#boundsdiv').offset();
var bx1 = bpos.left;
var bx2 = bpos.left + $('#boundsdiv').width();
var by1 = bpos.top;
var by2 = bpos.top + $('#boundsdiv').height();
// Check if it is inside and if not, reposition
if (x1 < bx1) { pos.left += (bx1 - x1); }
if (x2 > bx2) { pos.left -= (x2 - bx2); }
if (y1 < by1) { pos.top += (by1 - y1); }
if (y2 > by2) { pos.top -= (y2 - by2); }
// After calculating the final position, position it.
$(this).css({top: pos.top, left: pos.left});
}
});