简体   繁体   English

将滚动到所选项目的顶部

[英]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.在包含多个元素的ul中,我想滚动条以查看始终位于顶部的所选项目。 This item will have assigned the selected class.此项将分配selected类。 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:像这样遍历到parent元素:

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.我在类似的情况下使用了它:无法直接在scrollTop ... 行中遍历,因此我使用了一个变量来选择父级并将此变量放入scrollTop行中。

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

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