今天來簡單的寫一個吸頂,供大家參考,具體内容如下
先羅列一下吸頂需要使用到的屬性
** 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')
}
})
敬請期待 效果圖示(正在制作中…)
以上就是本文的全部内容,希望對大家的學習有所幫助,也希望大家多多支援腳本之家。