@vsync的优秀答案几乎满足了我的需求,但是我通过Grunt“uglify”我的代码,而Grunt需要一些较旧的JavaScript代码风格。这是我使用的调整后的脚本:
var stickyElm = document.getElementById('header');
var observer = new IntersectionObserver(function (_ref) {
var e = _ref[0];
return e.target.classList.toggle('isSticky', e.intersectionRatio < 1);
}, {
threshold: [1]
});
observer.observe( stickyElm );
那个答案中的CSS没有改变
对于固定的滚动高度,也可以像这样实现:
// select the header
const header = document.querySelector('header');
// add an event listener for scrolling
window.addEventListener('scroll', () => {
// add the 'stuck' class
if (window.scrollY >= 80) navbar.classList.add('stuck');
// remove the 'stuck' class
else navbar.classList.remove('stuck');
});
position: sticky
是Chrome实现的,所以我正在寻找一种可用的方法! - AlecRust