實際上,如果您使用一致且支持的getBoundingClientRect().top + body.scrollTop
的方式,這非常簡單 - 您現在必須做的就是從其中減少標題,因此只需獲取它並計算其高度即可。
var header = document.getElementById('container')
var clicks = document.querySelectorAll('#container li');
var content = document.querySelectorAll('#otherContainer > div');
// Turn the clicks HTML NodeList into an array so we can easily foreach
Array.prototype.slice.call(clicks).forEach(function(element, index){
element.addEventListener('click', function(e){
e.preventDefault();
// Set the scroll to the top of the element (top + scroll) minus the headers height
document.body.scrollTop = content[index].getBoundingClientRect().top + document.body.scrollTop - header.clientHeight;
});
});
#container {
position: fixed;
background: yellow;
width: 100%;
height: 50px;
}
ul li {
display: inline;
cursor: pointer;
}
#otherContainer {
padding-top: 60px
}
#first, #second, #third {
height: 500px
}
#first {
background: red
}
#second {
background: green
}
#third {
background: blue
}
<div id="container">
<ul>
<li id="jumpToFirst">first</li>
<li id="jumpToSecond">second</li>
<li id="jumpToThird">third</li>
</ul>
</div>
<div id="otherContainer">
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
</div>
這似乎是取決於你在移動的方向 - 基本上,它會嘗試到整個元素位置的視窗內和其完成時停止,所以當你向下滾動它將在底部像素點擊視口底部時停止,當您向上滾動時,頂部像素點擊視口頂部。但說實話,您可以輕鬆地執行'document.body.scrollTop = element.getBoundingClientRect()。top + document.body.scrollTop'滾動到所需位置 - 所有瀏覽器都支持並保持一致。 – somethinghere
@somethinghere與'document.body.scrollTop = element.getBoundingClientRect()。top + document.body.scrollTop'(https://jsfiddle.net/ahugp8bq/2/)相同的問題。你對你的分析是正確的,這也是記錄的行爲(以及我想要的)。問題在於它不關心其容器的位置。 –
哦,狗屎...簡單。使用'document.body.scrollTop = element.getBoundingClientRect()。top + document.body.scrollTop - header.clientHeight'將它們正確地對齊:)(使用'var header = document.getElementById('container')獲取頭文件' )。此外,您的示例小提琴看起來非常麻煩,因爲它爲每個小提琴定義了相同的代碼。 – somethinghere