<script type="text/javascript"> var header = document.getElementById('header');
var headerOriginalPos = header.offsetTop; // 获取元素原来的位置window.addEventListener('scroll', function() {var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;if (scrollTop >= headerOriginalPos) {header.style.position = 'fixed';header.style.top = '0';header.style.zIndex = '999';} else {header.style.position = 'static';}
});
</script>
<div id="header"> nav 需要吸顶的元素 页面内容</div>
<div id="content">
ddddddv
</div>
另外一个案例
1.scroll家族和offset家族的结合运用
2.当nav的offsetTop大于屏幕卷去高度的时候,进行吸顶
3.添加一个固定类,如果满足条件,为nav加类名
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title></title><style>*{margin: 0;padding: 0;list-style: none;border:none}img{vertical-align: top;width: 100%;}section{width: 70%;margin: 0 auto;}.nav{position: fixed;left: 0;top: 0;width: 100%}</style>
</head>
<body><header id="head"><img src="images/top.png" alt=""></header><nav id="nav"><img src="images/nav.png" alt=""></nav><section><img src="images/body01.png" alt=""><img src="images/body02.png" alt=""></section><script src="../../MyTools/MyTools.js"></script><script>window.addEventListener('load',function (ev) {// 1. 求出头部高度var navTopHeight = myTool.$('nav').offsetTop;// 2. 监听页面滚动window.addEventListener('scroll',function (ev1) {var scrollTopHeight = myTool.scroll().top;// 2.1 判断if(scrollTopHeight >= navTopHeight){myTool.addClassName(myTool.$('nav'),'nav')}else{myTool.removeClassName(myTool.$('nav'),'nav');}})})</script>
</body>
</html>