Document
* {
margin: 0;
padding: 0
}
.top {
height: 168px;
}
img {
vertical-align: top;
}
.main {
margin: 0 auto;
width: 1000px;
margin-top: 0px;
}
.fixed {
position: fixed;
top: 0;
left: 0;
}
// 页面滚动,滚动top的高度后,就实现导航栏固定,否则导航栏不固定
/*
思路分析
1. 页面增加滚动事件:window.onscroll
2. 滚动事件处理
2.1 获取页面滚动高度:window.pageYOffset
2.2 获取top的高度
2.3 判定:滚动的距离与top高度大小
2.3.1 如果大于:导航栏固定;nav.classList.add('fixed');
2.3.2 如果小于等于:导航栏不固定:nav.classList.remove('fixed');
*/
let a = document.getElementById('mainPart');
let b = document.getElementById('navBar');
// 先拿到mainPart的本身的marginTop值
let mainMargin = parseInt(getComputedStyle(a)['marginTop']);
console.log(mainMargin);
// console.log(b.offsetHeight);
// 1. 页面增加滚动事件:window.onscroll
window.onscroll = function () {
// 2. 滚动事件处理
// 2.1 获取页面滚动高度:window.pageYOffset
// 2.2 获取top的高度
let topPart = document.getElementById('topPart');
let navBar = document.getElementById('navBar');
let mainPart = document.getElementById('mainPart');
// console.log(topPart.offsetHeight, navBar.offsetHeight);
// 2.3 判定:滚动的距离与top高度大小
if (window.pageYOffset > topPart.offsetHeight) {
// 2.3.1 如果大于:导航栏固定;nav.classList.add('fixed');
navBar.classList.add('fixed');
// 细节:navBar脱标后,没有高度,导致main会顶上去
// 解决方案:给main增加一个marginTop属性,值是自己原来的值 + navBar的高度
mainPart.style.marginTop = mainMargin + navBar.offsetHeight + 'px';
} else {
// 2.3.2 如果小于等于:导航栏不固定:nav.classList.remove('fixed');
navBar.classList.remove('fixed');
// 不固定导航:减去导航栏的高度(回到原始状态)
mainPart.style.marginTop = mainMargin + 'px';
}
};
一键复制
编辑
Web IDE
原始数据
按行查看
历史