我正在使用锚点和部分创建一个单页网站。例如,当用户单击 Photography 时,jQuery将导航到该特定部分。
JavaScript / jQuery:
// When you click on an <a> that has a '#'
$('nav#primary-navwrapper a[href^="#"], #sitemap a[href^="#"]').bind('click.smoothscroll',function (e) {
// Prevent from default action to intitiate
e.preventDefault();
// Targets the part of the address that comes after the '#'
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
// The .offset() method allows us to retrieve the current position of an element relative to the document.
// Here we are using it to find the position of the target, which we defined earlier as the section of the address that will come after the '#'
'scrollTop': $target.offset().top - $('#header').outerHeight()
}, 500, 'swing', function () {
window.location.hash = target;
});
});
/**
* 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 - $('#header').outerHeight(); // 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");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("nav li:last-child a").addClass("nav-active");
}
}
});
这适用于所有浏览器,但我更改了以下行:
'scrollTop': $target.offset().top
到:
'scrollTop': $target.offset().top - $('#header').outerHeight()
(有关订单行,请参阅http://snippi.com/s/maod4ud。这是在第37行)
为了补偿我的position:fixed
标题,我减去了标题的高度。如果不这样做,标题将与内容重叠。
不幸的是,这在Firefox和IE中无法正常工作。你看到第一个转到正确的位置 - 标题高度,所以标题位于内容之上,但之后他立即再次前进。 (内容标题)
如何解决此问题?