2

我希望我的 jQuery UI AutoComplete 具有包含可用选项的动态窗口大小,但也具有最大高度,以便当返回大量选项时它不会占用整个页面。

当我有以下内容时,高度是动态的,但 maxHeight 被忽略:

    .ui-autocomplete {
    height: auto;
    max-height: 250px;
    overflow-y: auto;
    width:auto;
}

当我有以下内容时,高度不是动态的,但 maxHeight 有效:

    .ui-autocomplete {
    height: 250px;
    max-height: 250px;
    overflow-y: auto;
    width:auto;
}
4

4 回答 4

8

我的代码使用了 TJ 的绝佳示例 ( http://jsfiddle.net/s6XTu/12/ )。但是,如果您在页面上使用多个自动完成功能,则必须更改脚本中的某些行。您必须使用“自动完成(“小部件”)”作为参考。

    $('.ui-autocomplete').css('height', 'auto');
var $input = $(event.target),
    inputTop = $input.offset().top,
    inputHeight = $input.height(),
    autocompleteHeight = $input.autocomplete("widget").height(), // changed
    windowHeight = $(window).height();
if((inputHeight + autocompleteHeight) > (windowHeight - inputTop - inputHeight)) {
    $('.ui-autocomplete').css('height', (windowHeight - inputHeight - inputTop - 20) + 'px');
}
于 2012-09-25T14:24:20.860 回答
2

这里的基本思想是仅在自动完成小部件heightmax-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/

于 2012-07-03T00:51:15.963 回答
2

不要放 hiegh 只放 max-height ,它会起作用

.ui-autocomplete {
position: absolute;
top: 0;
left: 0;
cursor: default;
max-height: 145px;
overflow-y: auto; 
overflow-x: hidden;

}

于 2014-01-13T06:48:59.530 回答
0

这个解决方案对我有用。

.ui-autocomplete {
        overflow: auto;
        max-height: 150px !important;
    }

检查此图像。 在此处输入图像描述 在此处输入图像描述

于 2022-01-11T10:35:38.813 回答