简体   繁体   中英

How can I make selected item in listbox scroll to the top?

I creating a simple list off of array items. Scroll bars will appear if the list is big. However, my question is - when an item is selected, I would like to see that item to the top of the visible position, pushing all above items hidden above under scrollbar. So no matter what I item I select, it should be on top of the visible list box. This is not same as positioning the item to the top, just on the scrolling top. Hope my question is understood here.

Thanks for any help or direction I can get.

You can use this code:

$('#scrollable li').on('click', function(e){
    $('#scrollable').animate({scrollTop: $(e.target).position().top + $('#scrollable').scrollTop()});
});

See also this JSFiddle: http://jsfiddle.net/729nX/1/

after much googling, i found you can either use scrollTo() using javascript with a code similar to this

function scrollToElem(elem) {    
    if(pageElement != null){               
        window.scrollTo(elem.offsetTop, 0);    
    }
}
var elem= document.getElementById('your_element');
scrollToElem(elem);

or use use location.hash which seems to me the simplest solution with something alone the lines of

location.hash = '#' + 'your_element';

in case you have a scroll bar in an element instead of the whole window.

Element.scrollTop - MDN

Element.scrollTop - W3 school

function onSelect(list, selectedItem){
    list.scrollTop = selectedItem.offsetTop - list.offsetTop;
}

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