吸顶条顾名思义就是无论页面怎么动,吸顶条始终都在顶部。一般常用于各大电商网站的搜索栏。
实现代码:
首先布局网页css部分:
<style type="text/css">
#bigbox{
height:50px;
background:hotpink;
width:100%;
}
.move{
position: fixed;
top:0;
left:0;
}
.movetwo{
margin-top: 20px;
}
</style>
html部分:
<body style="height:3000px">
<p>aaa</p>
<p>bbb</p>
<p>ccc</p>
<p>ddd</p>
<p>eee</p>
<p>fff</p>
<p>ggg</p>
<div id="bigbox"></div>
</body>
接下来,就是js操作:
<script type="text/javascript">
window.onscroll = function(){ //onscroll屏幕滚动
//先获取div到浏览器上边界的距离
var top = bigbox.offsetTop;
//再获取滚动条到浏览器上边界的距离
var scTop = document.documentElement.scrollTop;
if(top<scTop){ //如果到顶部距离小于屏幕上边界的距离
bigbox.className = "move"; //更改样式
}else{ //如果到顶部距离大于屏幕上边界的距离
bigbox.className = "movetwo"; //移除move的样式
}
}
</script>