如何使用scrollTo插件滚动到元素的新位置

How to scroll to the new position of an element using the scrollTo plugin?

本文关键字:新位置 位置 元素 scrollTo 何使用 插件 滚动      更新时间:2023-09-26

我编写了一个jQuery点击事件处理程序,它隐藏了除一个元素外的所有元素,并使用scrollTo将窗口滚动到该元素的顶部,如下所示:

$(".jumbotron").click(function(){
            $('.jumbotron').not(this).toggle("slow");
            $.scrollTo($(this).position().top, 500);    
        });

但是窗口滚动到元素的旧位置,而它已经移动到另一个位置。如何隐藏所有其他元素并滚动到新位置?

最好在回调中这样做:

$(".jumbotron").click(function(){
   var $this = $(this); // cache it here
   $('.jumbotron').not(this).toggle("slow", function(){
      $.scrollTo($this.position().top, 500);
   });
});

。切换([duration] [, complete])

作为Jai提议的改进:

$(".jumbotron").click(function(){
   var that = this;
   $('.jumbotron').not(that).toggle("slow", function(){
      $.scrollTo(that, 500);
   });
});

这应该可以工作,scrollTo也接受DOMNodes和jQuery对象