JQuery UI自动完成:自动高度不尊重maxHeight

时间:2012-07-02 18:56:36

标签: css jquery-ui

我希望我的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;
}

3 个答案:

答案 0 :(得分:7)

我在代码中使用了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');
}

答案 1 :(得分:2)

这里的基本想法是,如果自动完成小部件的内容溢出height,则仅应用max-heightwindow。您可以使用以下方法检测到此信息:

//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/

答案 2 :(得分:2)

不要放高 只要把max-height,它就会起作用

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

}