简体   繁体   中英

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

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. Below is the code or you can see it on 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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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