滚动动画代码无法正常工作

时间:2015-04-09 12:07:27

标签: javascript jquery

嘿伙计我是jquery的绝对新手,这里是我的第一个脚本之一,它基本上假设在滚动到特定的部分时添加动画,小提琴是here

我在jquery中的滚动代码是:

$('nav a[href^="#"]').on('click', function (e) {
                e.preventDefault();

                $('nav a').each(function () {
                    $(this).removeClass('active');
                })
                $(this).addClass('active');

                var target = this.hash,
                   menu = target;
                $target = $(target);
                $('html, body').stop().animate({
                    'scrollTop': $target.offset().top
                }, 500, 'swing', function () {
                    window.location.hash = target;
                });
            }); 

现在我只知道JS中的基本调试,因此我在脚本中找到的唯一错误是target未定义。我从一个在线啧啧得到这个脚本,它在那里工作得很好,但我不知道为什么这里不起作用。

我无法理解作者添加未定义变量的意图。

有人可以指出我做错了什么吗?可以找到原始教程代码here

TY。 亚历-Z

1 个答案:

答案 0 :(得分:2)

您可能希望为html, body设置动画,而不是动画.content

$('.content').animate({
  'scrollTop': $target.offset().top
  }, 500, 'swing', function () {
   window.location.hash = target;
});

Fiddle

<小时/> 在此代码中:

var target = this.hash,

... this指的是点击的a元素,hash指的是其网址。

所以对于这个元素:

<a href="#ex-1">Example-1</a>

... this.hash将是#ex-1

<小时/> 这段代码:

$target = $(target);

...现在相当于:

$target = $('#ex-1');

...指的是div id

<小时/> 然后.content滚动到div的最高位置。