jQueryUI 自动完成结果列表在尝试滚动时会弹回顶部

jQueryUI AutoComplete results list springs back to top when attempting to scroll

本文关键字:滚动 顶部 列表 结果 jQueryUI      更新时间:2023-09-26

我正在尝试自定义jQueryUI自动完成小部件结果下拉列表的呈现以实现类似网格的显示样式,使用CSS限制高度并允许滚动(将max-heightoverflow-y: scroll相结合),但是我在滚动下拉列表本身时遇到了奇怪的行为:它会自动滚动回顶部和/或滚动只是将鼠标移到列表本身上。

您可以单击此处查看jsFiddle上的重现,或查看以下内容(代码可以放在本地html文件中并运行)。若要测试自动完成,请在文本框中输入字符串 val

<html>
<head>
<!-- Behavior seems consistent across jQuery/UI versions --> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
    var items = [];
    for (var i = 0; i < 100; i++) items.push('val' + i);
    var reference = $('#in1').autocomplete({ source: items });
    var broken = $('#in2').autocomplete({ source: items }).data('ui-autocomplete');
    var renderItem = function(ul,item) {
        var $li = $('<li />'); 
        var $a = $('<a />').css({width: '270px', float:'left', clear: 'both', padding:'0'}).appendTo($li);
        //Build fake "columns"
        for (var i = 0; i < 3; i++) 
            var $span = $('<span />').html('[Col'+i+item.value+'] ').appendTo($a);
        return $li.appendTo(ul);
    }
    broken._renderItem = renderItem;    
});
</script>
<style type="text/css">
* { font-family: Arial; font-size:12px; }
.ui-autocomplete {
    max-height: 100px;
    overflow-y: scroll;
    overflow-x: hidden;
}
</style>
</head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<body>
<strong>enter 'val' to test</strong>
SCROLLS OK: <input id="in1" type="text" /> SCROLLS WEIRD: <input id="in2" type="text" />
</body>
</html>

我回到了基础并重新检查了自动完成页面,但 AFAIK 我的代码是正确的。这是怎么回事?

好吧,

我可以告诉你是什么导致了这个问题。

它是由在以下行中添加float:'left'引起的:

var $a = $('<a />').css({width: '270px', /*float:'left',*/ clear: 'both', padding:'0'}).appendTo($li);