<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>吸顶demo</title>
<style>
*{
margin: 0;
padding: 0;
}
.nav-top{
width: 100%;
height: 80px;
background-color: aqua;
}
.nav-bar{
width: 100%;
height: 100px;
background-color: #cccccc;
}
.other{
width: 100%;
background-color: antiquewhite;
}
.other p{
margin: 150px;
}
.isFixed{
position: fixed;
top: 0;
}
</style>
</head>
<body>
<div class="nav-top">top</div>
<div class="nav-bar">
<p>导航条</p>
</div>
<div class="other">
<p>1111111</p>
<p>1111111</p>
<p>1111111</p>
<p>1111111</p>
<p>1111111</p>
<p>1111111</p>
<p>1111111</p>
</div>
</body>
<script type="text/javascript">
// querySelector IE8
var nav_bar = document.querySelector('.nav-bar'); // 获取需要吸顶的元素
function scrollHeight() {
let height = document.documentElement.scrollTop || document.body.scrollTop;
// classList兼容IE10+,可替换为一个函数处理class或者nav_bar.className = 'nav-bar isFixed'
height > 180 ? nav_bar.classList.add('isFixed') : nav_bar.className = 'nav-bar'
}
// addEventListener IE9,IE8使用attachEvent
window.addEventListener('scroll', scrollHeight)
</script>
</html>
效果图:
评论列表
已有0条评论