el.scrollIntoViewIfNeeded()如果它不在可见浏览器区域内,则滚动到 el
。一般来说,它工作正常,但我在将它与固定 header 一起使用时遇到问题。
我制作了一个示例片段:(该方法在 Firefox 中不起作用,因此演示也不起作用)https://jsfiddle.net/ahugp8bq/1/
一开始,所有三个彩色 div 都显示在固定标题下方。但是,如果您单击“second”,然后单击“first”,#first
的开头将位于标题后面,这是我不希望的。
问题似乎是 #otherContainer
的位置(它的 padding-top
)在向上滚动时几乎被忽略了。
最佳答案
实际上,如果您使用一致且受支持的 getBoundingClientRect().top + body.scrollTop
方式,这将非常简单 - 您现在要做的就是从中减少 header ,所以只需获取并计算它的高度。
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>
关于javascript - el.scrollIntoViewIfNeeded() 向上滚动太远,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872765/