如果输入框下方没有足够的空间来显示菜单,我试图让我的自动完成菜单在输入框上方打开。除了初始渲染之外,代码工作正常。 这意味着它在以下情况下始终显示在底部: 1.开始搜索 2. 单击字段并触发对字段中现有文本的搜索
我让它输出 position.my
和 position.at
内容,它们对于“上方”放置都是正确的,但它仍然显示在输入框下方。
我有一个名为 resize 的函数,它绑定(bind)到窗口滚动和调整大小。在您滚动页面的那一刻,菜单就会正确定位。我怀疑它是在完全渲染之前定位。
代码
_renderMenu 函数钩子(Hook)
// Autocomplete _renderMenu function
$(autocomplete_object)._renderMenu = function( ul, item ) {
var that = this;
jQuery.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
// Make sure the menu is now shown to calculate heights and etc (menu is now rendered, position rendering next)
jQuery(ul).show();
autocomplete.resize(ul, options);
autocomplete.create_dropdown_handlers(ul, options);
}
调整大小函数
// Resize function
function resize( ul, options ) {
var height;
// If the height of the results is smaller than the space available, set the height to the results height
var ul_height = 0;
jQuery(ul).find('li').each(function(i, element){
ul_height += jQuery(element).height();
});
// Make the height the full height available below the input box but above the window cut off
// Move the dropdown above the input box if there is not enough room below the input box
var $parent = jQuery("#" + options.name);
var padding = 25; // arbitrary number to prevent dropdown from hitting the window border in either direction
var bottom_distance = autocomplete.getViewportHeight() - ($parent.offset().top + $parent.height()) - padding;
var bottom_limit = 200;
var ul_position = {
my: "left top",
at : "left bottom",
of: $parent,
collision: 'none'
};
height = bottom_distance;
if (bottom_distance < bottom_limit) {
var top_distance = $parent.offset().top - padding;
height = top_distance;
// ----- It is getting here fine! -----
ul_position.my = "left bottom";
ul_position.at = "left top";
}
// We have room to show the entire dropdown results without a scrollbar
if (ul_height < height) {
height = 'auto';
}
// Position below or above parent depending on space
jQuery(ul).position(ul_position);
jQuery(ul).css({height: height == 'auto' ? height : height + 'px'});
}
TLDR:
jquery position 设置为显示在输入框上方,但它仍然显示在下方?
最佳答案
我最终不得不更新自动完成对象的位置值以及 ul 位置。我认为问题在于初始渲染会继承自动完成的位置变量(默认显示在输入框下方)。
这是新行:
// In the resize function after jQuery(ul).position(ul_position);
$parent.autocomplete("option", "position", ul_position); // Now the rendering is correct!
Resize函数添加
function resize (ul, options) {
...
calculate the height and position requirements
...
jQuery(ul).position(ul_position);
$parent.autocomplete("option", "position", ul_position); // <-- Addition to honor position for rendering
}
关于javascript - Jquery Position 在第一次通话时不兑现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21761407/