简体   繁体   English

Jquery自动完成导致页面不必要地滚动

[英]Jquery autocomplete causing page to scroll unnecessarily

I've got a frustrating issue with Jquery auto-complete. Jquery 自动完成有一个令人沮丧的问题。 I have UL of drop down options which appears beneath the input.我有 UL 下拉选项出现在输入下方。 The ui-menu and ui-menu-items are being rendered with width:1214px - I assume this is document width or something. ui-menuui-menu-itemswidth:1214px呈现 - 我假设这是文档宽度或其他东西。 I don't know why this happens, but I can overwrite the CSS to fix it.我不知道为什么会发生这种情况,但我可以覆盖 CSS 来修复它。

Fixing the width causes line breaks in the result list, which is fine.固定宽度会导致结果列表中出现换行符,这很好。 The limited result list still easily fits on the page but for some reason the page height is thrown off and I get a vertical scroll bar.有限的结果列表仍然很容易适合页面,但由于某种原因页面高度被抛出,我得到一个垂直滚动条。

All the ul and li heights are set to auto in the DOM explorer- why does it cause the page to scroll?所有ulli高度在 DOM 资源管理器中都设置为auto - 为什么会导致页面滚动?

What workarounds are there to keep the autocomplete box inside the lines?有什么解决方法可以将自动完成框保持在行内?

CSS: CSS:

.ui-menu {
  ...
  width:245px;
}
.ui-menu-item{
  cursor:pointer;
  list-style: none;
  ...
  width:245px;
}

JS: JS:

$.ui.autocomplete.prototype._renderMenu = function( ul, items ) {
  var self = this;
  $.each( items, function( index, item ) {
    if (index < 10)
      {self._renderItem( ul, item );}
  });
}

Input:输入:

<input type="text" class="Search" id="search_box"/>

I solved this problem using the appendTo initialization option.我使用appendTo初始化选项解决了这个问题。 I think that the problem is that the absolutely position autocomplete menu is still increasing the height of the body: by setting the appendTo option to a div with height: 0px , I was able to eliminate the problem.我认为问题在于绝对位置自动完成菜单仍在增加主体的高度:通过将 appendTo 选项设置为height: 0px的 div ,我能够消除该问题。

Example:例子:

Javascript: Javascript:

$( ".selector" ).autocomplete({
  appendTo: "#hidden-stuff"
});

HTML: HTML:

<body>
  <input class="selector" type="text>
  <div id="hidden-stuff" style="height: 0px;"></div>
</body>

Try to set/overwrite the z-index of the list that drops down on search:尝试设置/覆盖搜索下拉列表的 z-index:

z-index:999 or z-index:1000

I am not sure but it could help.我不确定,但它可能会有所帮助。 Another solution would be to set the overflow to hidden when user is searching:另一种解决方案是在用户搜索时将溢出设置为隐藏:

So as soon as the user clicks on the input field:因此,只要用户单击输入字段:

$("html,body").css("overflow","hidden");

And when the input field looses focus:当输入字段失去焦点时:

$("html,body").css("overflow","auto");

However this seems strange to me because jQuery UI should work properly.然而这对我来说似乎很奇怪,因为 jQuery UI 应该可以正常工作。

Just place position: fixed into the CSS class ui-autocomplete like this:只需将位置:固定到 CSS 类ui-autocomplete 中,如下所示:

.ui-autocomplete  
{
    position: fixed; /* Prevents page scroll when autosuggestion menu appears */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM