我对JavaScript非常陌生,所以我提前道歉。我正在尝试使用导航链接列表为学校项目创建一个单页html文档,该链接在锚点滚动到时会发生变化。我尝试过在Jfiddle和stackoverflow上找到的各种不同的方法。这是我现在尝试的方法:http://jsfiddle.net/m2zQE/
var topRange = 200, // measure from the top of the viewport to X pixels down
edgeMargin = 20, // margin above the top or margin from the end of the page
animationTime = 1200, // time in milliseconds
contentTop = [];
$(document).ready(function () {
// Stop animated scroll if the user does something
$('html,body').bind('scroll mousedown DOMMouseScroll mousewheel keyup', function (e) {
if (e.which > 0 || e.type == 'mousedown' || e.type == 'mousewheel') {
$('html,body').stop();
}
});
// Set up content an array of locations
$('#nav').find('a').each(function () {
contentTop.push($($(this).attr('href')).offset().top);
});
// Animate menu scroll to content
$('#nav').find('a').click(function () {
var sel = this,
newTop = Math.min(contentTop[$('#nav a').index($(this))], $(document).height() - $(window).height()); // get content top or top position if at the document bottom
$('html,body').stop().animate({
'scrollTop': newTop
}, animationTime, function () {
window.location.hash = $(sel).attr('href');
});
return false;
});
// adjust side menu
$(window).scroll(function () {
var winTop = $(window).scrollTop(),
bodyHt = $(document).height(),
vpHt = $(window).height() + edgeMargin; // viewport height + margin
$.each(contentTop, function (i, loc) {
if ((loc > winTop - edgeMargin && (loc < winTop + topRange || (winTop + vpHt) >= bodyHt))) {
$('#nav li')
.removeClass('selected')
.eq(i).addClass('selected');
}
});
});
});
我还没有运气。我已经搜索过我是否可以调试问题并尝试更改代码的顺序以及调用jquery的顺序。
以下是该网站的链接:https://googledrive.com/host/0BwvPQbnPrz_LMlZDeGlFY2Yydmc/index.html
我用html5boilerplate作为起点。提前谢谢你。
答案 0 :(得分:0)
没有太多时间查看您的代码,但是当我输入行
时Math.min(contentTop[$('#nav a').index($(this))], $(document).height() - $(window).height())
进入开发人员工具的控制台,它返回NaN。
所以我猜问题是你没有正确设置你的scrollTop。
我建议你给每个元素一个id并尝试:
$('html, body').animate({
scrollTop: $("#elementID").offset().top
}, 2000);
或者如果你坚持不给id,
$('html, body').animate({
scrollTop: $("#container-fulid:nth-child(2)").offset().top
}, 2000);
但请注意,这不适用于所有浏览器,因为nth-child选择器是CSS3选择器。
或者,如果您知道如何正确使用其他人的工作,您可以尝试使用bootstrap 3.0,其中已经包含了一个名为scrollspy的函数,它正是您正在做的事情。