2016-03-08 65 views
0

el.scrollIntoViewIfNeeded()如果滚动条不在可见浏览器区域内,则滚动到el。一般来说,它工作正常,但我有一个固定的头使用它的问题。el.scrollIntoViewIfNeeded()滚动得太快

我提出的示例代码段:(该方法不工作在Firefox,所以同样没有演示)https://jsfiddle.net/ahugp8bq/1/

在开始时所有三种颜色的div被显示在固定报头的下方。但是,如果你点击“第二”然后“第一”,那么#first的开头将会在标题后面,我不想要。

这个问题似乎是在滚动时忽略了#otherContainer(它的padding-top)的位置。

+0

这似乎是取决于你在移动的方向 - 基本上,它会尝试到整个元素位置的视窗内和其完成时停止,所以当你向下滚动它将在底部像素点击视口底部时停止,当您向上滚动时,顶部像素点击视口顶部。但说实话,您可以轻松地执行'document.body.scrollTop = element.getBoundingClientRect()。top + document.body.scrollTop'滚动到所需位置 - 所有浏览器都支持并保持一致。 – somethinghere

+0

@somethinghere与'document.body.scrollTop = element.getBoundingClientRect()。top + document.body.scrollTop'(https://jsfiddle.net/ahugp8bq/2/)相同的问题。你对你的分析是正确的,这也是记录的行为(以及我想要的)。问题在于它不关心其容器的位置。 –

+0

哦,狗屎...简单。使用'document.body.scrollTop = element.getBoundingClientRect()。top + document.body.scrollTop - header.clientHeight'将它们正确地对齐:)(使用'var header = document.getElementById('container')获取头文件' )。此外,您的示例小提琴看起来非常麻烦,因为它为每个小提琴定义了相同的代码。 – somethinghere

回答

0

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

+0

虽然这不是'el.scrollIntoViewIfNeeded(false)'行为。 'el.scrollIntoViewIfNeeded'只在'el'不在视口中时才会滚动,并且它会滚动到顶部或底部,具体取决于哪个更接近。当然,我可以自己实现这个逻辑,但是因为'el.scrollIntoViewIfNeeded'一般工作得很好,我想可能只是一个小小的调整(例如在CSS中)。 –