アンカー ポイントとセクションを使用して 1 ページのサイトを作成しています。たとえば、ユーザーが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 では正しく機能しません。最初にヘッダーの高さの正しい位置に移動することがわかります。そのため、ヘッダーはコンテンツの上に配置されますが、その後すぐに元の位置に戻ります。(コンテンツ上のヘッダー)
この問題を解決するにはどうすればよいですか?