滚动到所选项目的顶部

Move scroll to top with the selected item

本文关键字:顶部 项目 选项 滚动      更新时间:2023-10-16

在一个包含多个元素的ul中,我想滚动条以查看所选项目始终位于顶部。此项目将分配selected类。到目前为止,我已经设法将条滚动到该元素的位置,但没有将其滚动到容器的顶部。

我的代码是:

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

知道吗?

遍历parent元素,如下所示:

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

我在类似的情况下使用了这个:不可能在scrollTop中直接遍历。。。行,所以我使用了一个变量来选择父级,并将这个变量放入scrollTop行。