今天来简单的写一个吸顶,供大家参考,具体内容如下
先罗列一下吸顶需要使用到的属性
** scrollTop 获取当前滚动的距离(也就是盒子距离顶部的距离)
offsetTop 盒子距离顶部的高度
offsetHeight 盒子自身的高度
scrollY 滚动的距离
**
想要写出一个吸顶 一定要先明白这几个属性哦(当然了,他也很简单,相信您看完会有一定的收获)
根据图片中的思路来写:
Document*{
margin:0;
padding:0;
box-sizing:border-box;
}
.wrap{
overflow-y:scroll;
}
.header{
width: 100%;
height: 40px;
background: lightgreen;
color:#fff;
text-align: center;
line-height: 40px;
}
.main{
height: 1000px;
background: lightyellow;
}
.fixed{
position: fixed;
top:0;
}
const head = document.querySelector('.header');
document.addEventListener('scroll',()=>{
//console.log(document.documentElement.offsetTop) // 0 html距离顶部的距离
//console.log(document.querySelector('.header').offsetHeight) // 40 红盒子的高度
//console.log(window.scrollY) // 滚动的距离
if(window.scrollY > head.offsetHeight){
head.classList.add('fixed')
}
})
敬请期待 效果图示(正在制作中…)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。