2016-08-18 54 views
1

的頂部固定橫幅的元素我已想出如何使scrollTop的是這樣的:.scrollTop與屏幕上的

$("#nav-home").click(function() { 
    $('html, body').animate({scrollTop: $("#content-home").offset().top}, 800); 
}); 

但我的問題是,我已經在屏幕頂部的固定橫幅所以當它滾動頁面部分的#content-home元素被橫幅所隱藏。

我也是用這個:

var hheight = $(".mainh").height(); 
var theight = hheight + 14; 
$("#first-content").css("margin-top", mheight + "px") 

取決於旗幟+ 2 * 7px的邊界(+ 14)的高度自動添加上邊距。我知道這很愚蠢,但我很滿意這種方式。

所以我要求的東西就像增加更多的偏移量。或者可以添加上面提到的「邊距計算器」影響的第一個元素的偏移量。

如果你能幫我解決這個問題,甚至可以添加一些提示,我會很開心。

回答

1

爲什麼不減去旗幟的高度與scrollTop多少?

var contentTop = $("#content-home").offset().top; 
var hheight = $(".mainh").outerHeight(true); // the 'true' in the statement will include the top and bottom margin of the element, if they exist. 
var scrollTopY = contentTop - hheight; 

$("#nav-home").click(function() { 
    $('html, body').animate({scrollTop: scrollTopY}, 800); 
}); 
+0

謝謝你,你的回答幫了我。但是我必須用「 - hheight」替換「+ hheight」,出於某種原因,當我有+時,它完美滾動,但是在內容之後的下一個元素。我真的不知道爲什麼這樣做,但我真的不在乎,因爲它現在工作正常。 – MasterTX

+0

@MasterTX你是對的,當然,我們應該減去標題的高度,而不是添加它!我的答案已經被修改來解決這個問題〜 –

0

使用本

$( 'mainh')。outerHeight(真)