实际上,如果您使用一致且支持的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