我正在使用锚点和部分创建一个单页网站。例如,当用户单击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 中无法正常工作。您会看到第一个转到正确的位置 - 标题高度,因此标题位于内容上方,但随后他再次像以前一样站立。(内容上方的标题)
我该如何解决这个问题?