如何禁用jQuery UI Autocomplete中的鼠标悬停滚动功能?
解决jQuery UI Autocomplete悬停最后一项自动滚动的问题
完全可以实现禁用该功能,这个自动滚动是jQuery UI Autocomplete内部的菜单交互逻辑控制的,你可以通过重写对应的原型方法来取消该行为:
方案一:重写Autocomplete的_move方法
这个方法负责处理鼠标/键盘导航时的菜单项聚焦与滚动,注释掉其中触发自动滚动的逻辑即可:
$.ui.autocomplete.prototype._move = function( direction, event ) { if ( !this.menu.element.is( ":visible" ) ) { this.search( null, event ); return; } if ( this.menu.active ) { var next = this.menu.active[ direction + "All" ]( ".ui-menu-item" ).eq( 0 ); if ( next.length ) { this.menu.focus( event, next ); } // 注释掉原有的自动滚动触发代码 // } else { // this.menu.focus( event, this.menu.element.children( ".ui-menu-item" ).eq( direction === "next" ? 0 : -1 ) ); } else { this.menu.focus( event, this.menu.element.children( ".ui-menu-item" ).eq( 0 ) ); } };
方案二:重写Menu的focus方法
如果只想禁用聚焦时的自动滚动,直接覆盖菜单的focus方法,移除其中的滚动调用:
$.ui.menu.prototype.focus = function( event, item ) { var prev = this.active; this.active = item || $( this.element.find( ".ui-menu-item" ).get( 0 ) ); if ( prev && prev.length ) { prev.removeClass( "ui-state-active" ); } if ( this.active.length ) { this.active.addClass( "ui-state-active" ); // 注释掉自动滚动到视图内的代码 // this._scrollIntoView(); } };
注意事项:
- 重写原型方法的代码要放在你初始化Autocomplete的代码之前,确保覆盖生效
- 不同版本的jQuery UI可能方法细节略有差异,核心是找到控制滚动的
_scrollIntoView调用或相关逻辑,将其移除即可
内容的提问来源于stack exchange,提问作者Tiago Dantas
相关产品推荐
相关产品推荐

