简体   繁体   English

如何使用jQuery / JS将列表框滚动到顶部

[英]How do I use jQuery/JS to scroll a listbox to the top

JSFiddle JSFiddle

In the fiddle example I have several attempts to scroll a listbox to the top (or any point in the list) after programmatically selecting an item. 在小提琴示例中,我有几次尝试以编程方式选择项目后将列表框滚动到顶部(或列表中的任何点)。 I have not been able to find a way that works or an example on SO that shows how to successfully do this. 我还没有找到一种可行的方法或一个SO示例来说明如何成功实现这一目标。 Below is the code or you can see it on JSFiddle. 下面是代码,或者您可以在JSFiddle上看到它。 Can someone point me in the right direction please. 有人可以指出我正确的方向。

<select id='focusScrollTest' multiple='multiple'>
    <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>

$(document).ready(function(){
//return the current scroll position before selecting the last option
var x = $("#focusScrollTest").scrollTop();

//Displays 0
//alert(x);

//Select the last option value
$("#focusScrollTest option[value='9']").attr('selected', 'selected');

//return the current scroll position after selecting the last option
var y = $("#focusScrollTest").scrollTop();

//Displays 85
//alert(y);

///
///   These do not change the scroll
///
//$("#focusScrollTest option[value='1']").scrollTo();
//$("#focusScrollTest option[value='1']").scrollTo(0);
//$("#focusScrollTest").scrollTo(x);
//$("#focusScrollTest").scrollTo(0);
//$("#focusScrollTest").scrollTo(1);
//$("#focusScrollTest").scrollTop = 0;
//$("#focusScrollTest option[value='1']").scrollTop = 0;
//$("#focusScrollTest").focus();
//$("#focusScrollTest option[value='1']").focus();
//$("#focusScrollTest").blur().focus();
//$("#focusScrollTest option[value='1']").blur().focus();

//This is very interesting, even though it is done last the box
//still scrolled to the end
//$("#focusScrollTest option[value='1']").attr('selected', 'selected');

}); });

Try this: 尝试这个:

http://jsfiddle.net/jLzpU/ http://jsfiddle.net/jLzpU/

$('#focusScrollTest').scrollTop(0); 

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

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