初学者记载学习的日程收获
先使用js中获取进度条位置的属性scrollTop,她的兼容写法为
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
运用逻辑短路的方法,当 || 前面的属性不能拿到正确的值时,那么就用 || 后面的属性获取值
而后
调用窗口滚动对象window.onscroll
window.onscroll = function () {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
}
建立判断条件,如果页面滚动的值超过导航栏的高度navHeight时,将导航栏的position属性值改为fixed,top值可以设置为0px,由于导航栏position属性值的改变会推脱离文档流,所以将下面的内容块的margin-top值改成导航栏的高度height
if (scrollTop >= 90) {
sBox.style.position = ‘fixed’;//sBox是导航栏
sBox.style.top = ‘0px’;
tBox.style.margin = ‘110px,0,0’//tBox是内容块
}
补充
当页面回到顶端时,需要再次显示为原来默认的状态,所以把导航栏的position值改为默认的static,内容块的margin值也要还原
else {
sBox.style.position = ‘static’;
tBox.style.margin = ‘0’;
}
完整代码如下
div:nth-child(1) {
width: 100%;
height: 80px;
background: pink;
}
div:nth-child(2) {
width: 100%;
height: 100px;
background: powderblue;
}
div:nth-child(3) {
width: 100%;
height: 1300px;
background: plum;
}
span {
display: block;
width: 200px;
height: 1000px;
margin: 0 auto;
background: orange;
}
js部分
var fBox = document.getElementById(‘first’),
sBox = document.getElementById(‘second’),
tBox = document.getElementById(‘third’);
window.onscroll = function () {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop >= 90) {
sBox.style.position = ‘fixed’;
sBox.style.top = ‘0px’;
tBox.style.margin = ‘110px,0,0’
}
else {
sBox.style.position = ‘static’;
tBox.style.margin = ‘0’
}
}