js實現(xiàn)移動端吸頂效果
更新時間:2020年01月08日 09:32:33 作者:六月~
這篇文章主要為大家詳細介紹了js實現(xiàn)移動端吸頂效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
今天來簡單的寫一個吸頂,供大家參考,具體內容如下
先羅列一下吸頂需要使用到的屬性
** scrollTop 獲取當前滾動的距離(也就是盒子距離頂部的距離)
offsetTop 盒子距離頂部的高度
offsetHeight 盒子自身的高度
scrollY 滾動的距離
**
想要寫出一個吸頂 一定要先明白這幾個屬性哦(當然了,他也很簡單,相信您看完會有一定的收獲)

根據(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) // 滾動的距離
if(window.scrollY > head.offsetHeight){
head.classList.add('fixed')
}
})
</script>
</body>
</html>
敬請期待 效果圖示(正在制作中…)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
js獲取iframe中的window對象的實現(xiàn)方法
下面小編就為大家?guī)硪黄狫S獲得iframe中的window對象的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05
layui?框架的upload上傳文件的data參數(shù)傳到后端的方法
這篇文章主要介紹了layui框架的upload上傳文件的data參數(shù)傳到后端的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11

