这里的基本思想是仅在自动完成小部件height
的max-height
内容溢出window
. 您可以使用以下方法检测到这一点:
//Reset the height so the true height can be calculated.
$('.ui-autocomplete').css('height', 'auto');
//Get some values needed to determine whether the widget is on
//the screen
var $input = $('#the-id-of-the-input-node'),
inputTop = $input.offset().top,
inputHeight = $input.height(),
autocompleteHeight = $('.ui-autocomplete').height(),
windowHeight = $(window).height();
//The widget has left the screen if the input's height plus it's offset from the top of
//the screen, plus the height of the autocomplete are greater than the height of the
//window.
if ((inputHeight + inputTop + autocompleteHeight) > windowHeight) {
//Set the new height of the autocomplete to the height of the window, minus the
//height of the input and the offset of the input from the top of the screen. The
//20 is simply there to give some spacing between the bottom of the screen and the
//bottom of the autocomplete widget.
$('.ui-autocomplete')
.css('height', (windowHeight - inputHeight - inputTop - 20) + 'px');
}
在 CSS 中,您还需要设置 ,以便在其内容不适合其容器overflow
时出现滚动条。ui-autocomplete
.ui-autocomplete { overflow: auto; }
我有一个活生生的例子在这里展示 - http://jsfiddle.net/s6XTu/12/。