原生js實(shí)現(xiàn)吸頂效果
實(shí)現(xiàn)思路如下:
1. div初始居普通文檔流中
2. 給window添加scroll事件(可事件節(jié)流),獲取div的offset的top值,滾動(dòng)時(shí)scrollTop值和top比較,當(dāng)?shù)竭_(dá)top時(shí)給div添加一個(gè)fixed的class使其固定
3. 向上滾動(dòng)時(shí)當(dāng)?shù)竭_(dá)div初始top時(shí)則刪除fixed的class,此時(shí)div又回到普通文檔流中
4. fixed樣式非IE6瀏覽器使用position:fixed,IE6使用position:absolute和IE expression
效果圖:

代碼如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無(wú)標(biāo)題文檔</title>
<style>
* {
margin: 0;
padding: 0;
}
#div1 {
width: 100%;
height: 50px;
background: skyblue;
}
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById('div1');
var divT = oDiv.offsetTop;
//console.log(divT);
window.onscroll = function() {
// 獲取當(dāng)前頁(yè)面的滾動(dòng)條縱坐標(biāo)位置 (依次為火狐谷歌、safari、IE678)
var scrollT = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
if (scrollT >= divT) {
if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1) {
// 兼容IE6代碼
oDiv.style.position = 'absolute';
oDiv.style.top = scrollT + 'px';
oDiv.style.left = 0 + 'px';
} else {
// 正常瀏覽器代碼
oDiv.style.position = 'fixed';
oDiv.style.top = 0;
oDiv.style.left = 0;
}
} else
oDiv.style.position = '';
}
}
</script>
</head>
<body>
<div class="all">
以上<br>
以上<br>
以上<br>
以上<br>
以上<br>
以上<br>
以上<br>
<div id="div1"></div>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
啦啦啦啦啦<br>
</div>
</body>
</html>
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
JavaScript中apply與call的用法意義及區(qū)別說(shuō)明
JavaScript中有一個(gè)call和apply方法,其作用基本相同,但也有略微的區(qū)別。2010-04-04
JavaScript運(yùn)動(dòng)框架 解決速度正負(fù)取整問(wèn)題(一)
javascript實(shí)現(xiàn)3D切換焦點(diǎn)圖
Javascript-Mozilla和IE中的一個(gè)函數(shù)直接量的問(wèn)題
js中如何將多層嵌套的數(shù)組轉(zhuǎn)換為一層數(shù)組
js實(shí)現(xiàn)的鼠標(biāo)滾輪滾動(dòng)切換頁(yè)面效果(類似360默認(rèn)頁(yè)面滾動(dòng)切換效果)

