简体   繁体   中英

Move scroll to top with the selected item

In a ul of multiple elements, I would like to scroll the bar to see the selected item always on the top. This item will have assigned the selected class. Up to now, I have managed to scroll the bar to the position of this element but not to scroll it to the top of the container.

My code is:

jQuery(document).ready(function(){
    jQuery('#container').animate({
        scrollTop: jQuery('li.selected').offset().top
    }, 2000);
});

Any idea?

Traverse to the parent element like this:

jQuery(document).ready(function(){
    var x = jQuery('li.selected').parent();
    jQuery('#container').animate({
        scrollTop: jQuery(x).offset().top
    }, 2000);
});

I used this in a similar situation: It was not possible to traverse directly in the scrollTop ... line, so I used a variable to select the parent and put this variable into the scrollTop line.

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