js實(shí)現(xiàn)移動(dòng)端吸頂效果
今天來簡(jiǎn)單的寫一個(gè)吸頂,供大家參考,具體內(nèi)容如下
先羅列一下吸頂需要使用到的屬性
** scrollTop 獲取當(dāng)前滾動(dòng)的距離(也就是盒子距離頂部的距離)
offsetTop 盒子距離頂部的高度
offsetHeight 盒子自身的高度
scrollY 滾動(dòng)的距離
**
想要寫出一個(gè)吸頂 一定要先明白這幾個(gè)屬性哦(當(dāng)然了,他也很簡(jiǎn)單,相信您看完會(huì)有一定的收獲)

根據(jù)圖片中的思路來寫:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
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;
}
</style>
</head>
<body>
<div class="wrap">
<div class="header">我是即將吸頂?shù)呐?lt;/div>
<div class="main"></div>
</div>
<script>
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) // 滾動(dòng)的距離
if(window.scrollY > head.offsetHeight){
head.classList.add('fixed')
}
})
</script>
</body>
</html>
敬請(qǐng)期待 效果圖示(正在制作中…)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Web?Components使用生命周期回調(diào)函數(shù)實(shí)例詳解
這篇文章主要為大家介紹了Web?Components使用生命周期回調(diào)函數(shù)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
js獲取瀏覽器的可視區(qū)域尺寸的實(shí)現(xiàn)代碼
js獲取瀏覽器的可視區(qū)域尺寸的實(shí)現(xiàn)代碼,需要的朋友可以參考下。2011-11-11
JavaScript對(duì)數(shù)字的判斷與處理實(shí)例分析
這篇文章主要介紹了JavaScript對(duì)數(shù)字的判斷與處理方法,實(shí)例分析了javascript判斷數(shù)字的常見方法與針對(duì)數(shù)字處理的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-02-02
JS組件Bootstrap ContextMenu右鍵菜單使用方法
這篇文章主要為大家詳細(xì)介紹了JS組件Bootstrap ContextMenu右鍵菜單使用方法,感興趣的小伙伴們可以參考一下2016-04-04
JS實(shí)現(xiàn)點(diǎn)餐自動(dòng)選擇框(案例分析)
這篇文章主要介紹了JS實(shí)現(xiàn)點(diǎn)餐自動(dòng)選擇框功能,點(diǎn)擊上方全選和全不選選擇框?qū)崿F(xiàn)對(duì)應(yīng)功能,本文分步驟通過實(shí)例代碼講解的非常詳細(xì),需要的朋友可以參考下2019-12-12

