我忙于创建单页设计。现在我对网站的导航部分有一些问题。当我点击菜单中的项目时,我搜索了一个跳转到特定锚点的代码。同样值得一提的是我有一个固定的标题。
我想出了这段代码:
$(document).ready(function(){
// An offset to push the content down from the top
var offset = $('#header').outerHeight();
function scrollToAnchor( anchor ) {
$("html, body").animate({ scrollTop: $(anchor).position() - offset });
}
// When you click on an <a> that has a '#'
$('nav#primary-navwrapper a[href^="#"], #sitemap a[href^="#"], .hireme a[href^="#"]').bind('click.smoothscroll',function (event) {
// Prevent from default action to intitiate
// The id of the section we want to go to.
var id = $(this).attr("href");
// Our scroll target : the top position of the
// section that has the id referenced by our href.
var target = $(id).offset().top - offset;
console.log(target);
// The magic...smooth scrollin' goodness.
$('html, body').animate({ scrollTop:target }, 500);
// Prevent the page from jumping down to our section.
event.preventDefault();
return false;
});
/**
* This part handles the highlighting functionality.
* We use the scroll functionality again, some array creation and
* manipulation, class adding and class removing, and conditional testing
*/
var aChildren = $('#primary-navwrapper li').children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().top - offset; // get the offset of the div from the top of page
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass('current');
} else {
$("a[href='" + theID + "']").removeClass('current');
}
}
});
//now scroll to the anchor when loading page - this was missing
scrollToAnchor(document.location.hash);
});
但我对这段代码有些麻烦。 首先,我认为这段代码可以比现在短得多,这是正确的吗? 第二,当我在网站(不是主页)的登陆页面上,我想回去时,平滑滚动不起作用。我以为这是缺少的部分:
scrollToAnchor(document.location.hash);
第三,我在开发人员工具中遇到了这个错误:
Uncaught TypeError: Cannot read property 'top' of undefined