大家好,我是 jquery 的绝对新手,这是我的第一个脚本之一,它基本上假设在滚动到特定部分时基本上添加动画, fiddle 是 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
。我从在线 tut 那里得到了这个脚本,它在那里工作得很好,但我不知道为什么它在这里不起作用。
我无法理解作者添加 undefined variable 的意图。
有人可以指出我做错了什么吗?原始教程代码可以找到here .
泰。 亚历克斯-z
最佳答案
您可能想要为 .content
设置动画,而不是为 html, body
设置动画:
$('.content').animate({
'scrollTop': $target.offset().top
}, 500, 'swing', function () {
window.location.hash = target;
});
在这段代码中:
var target = this.hash,
... this
指的是被点击的a
元素,hash
指的是它的URL。
所以对于这个元素:
<a href="#ex-1">Example-1</a>
... this.hash
将是 #ex-1
。
这段代码:
$target = $(target);
... 现在等同于:
$target = $('#ex-1');
… 引用具有该 id
的 div
。
.content
然后滚动到该 div
的顶部位置。
关于javascript - 滚动动画代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29538071/