简体   繁体   English

滚动到html列表框中的选定项目

[英]scroll to selected item in html listbox

I have an html listbox : 我有一个HTML列表框:

<select id="test" size="5">           
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>

I am trying to select an item via code and have the listbox automatically scroll to the selected item. 我正在尝试通过代码选择一个项目,并使列表框自动滚动到所选项目。

Is this supposed to scroll the listbox automatically to the selected item ? 是否应该将列表框自动滚动到所选项目?

$('#test option[value="8"]').attr('selected', 'selected');

I can't seem to get it to do that ... am I missing something ? 我似乎无法做到这一点...我错过了什么吗?

Setting the selected item will only cause the item to be visible within the select field, but doesn't guarantee that it will be at the top of the list of items shown. 设置所选项目只会使该项目在选择字段中可见,但不能保证它会在显示的项目列表的顶部。 I tried this in a jsfiddle and you'll see your code highlights the #8, but it's at the bottom of the select field box. 我在jsfiddle中进行了尝试,您会看到代码突出显示了#8,但它位于选择字段框的底部。 http://jsfiddle.net/Ck4m3/ http://jsfiddle.net/Ck4m3/

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

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