我希望我的.row-navigation
行在position-fixed
滚动时出现。所以我过去常常window.onscroll
听滚动事件并在滚动时将类分配.sticky
给.row-navgation
行。在过程getBoundingClientRect().top
中使用。
出乎意料的行为:
当滚动事件发生时,每个备用像素滚动都会getBoundingClientRect().top
返回。结果滚动时行闪烁0
.row-navigation
在codepen上检查这个 https://codepen.io/neel111/pen/NVaEyB
<div class="container">
<div class="row-welcome"></div>
<div class="row-navigation"></div>
</div>
.row-welcome {
height: 34px;
background-color: yellow;
}
.row-navigation {
height: 80px;
background-color: #000;
}
.row-navigation.sticky {
position: fixed;
top: 0;
width: 100%;
}
window.onscroll = function() {
var rowNavigation = document.querySelector('.row-navigation');
var nextDomElement = rowNavigation.parentElement.nextElementSibling;
console.log(rowNavigation.getBoundingClientRect().top, rowNavigation.getBoundingClientRect().right, rowNavigation.getBoundingClientRect().bottom);
if (0 > rowNavigation.getBoundingClientRect().top) {
rowNavigation.classList.add('sticky');
} else {
rowNavigation.classList.remove('sticky');
}
}
如何解决的意外行为getBoundingClientRect().top
?