2012-07-02 81 views
2

我想我的jQuery UI自动完成具有包含可用选项的动态窗口大小,但也有一个最大高度,以便当有大量选项返回时不占用整个页面。JQuery UI自动完成:自动高度不尊重maxHeight

当我有以下,高度动态的,但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; 
} 
+0

你有什么应该是工作。我可以在jQuery演示页面上重现结果。我的猜测是某处出现CSS冲突。检查你的浏览器开发工具以确保CSS得到应用。尝试添加!对于高度规则来说很重要(只是为了测试,修正CSS,不要把它放在重要的位置)。 – BZink

+0

如果您需要避免元素在页面上熄灭:您可以尝试:位置:{my:“left top”,at:“left bottom”,collision:“flipfit”},在自动完成函数中:https:// api。 jqueryui.com/autocomplete/#option-position –

回答

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'); 
} 
+0

注意:如果您使用回调进行建议,则event.target可能不是输入。我*认为*使用'这'是更可靠的。 – OlduwanSteve

2

基本如果自动填充小部件的内容溢出window,则此处的想法仅应用heightmax-height。你可以用下面这个检测:

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

+0

谢谢你。一个*非常*小调:在你的小提琴中,你用event.target来获得输入。如果导致打开的事件不是源于输入,那么这不起作用。在我的情况下,我正在远程获取建议,因此事件目标实际上是请求对象。我把它改为'this',这似乎是迄今为止工作。 – OlduwanSteve

2

不要把hieght 只要把最大高度,它将工作

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

}