css代码
<style type="text/css">
*{
padding: 0px;
margin: 0px;
list-style: none;
font-family: "微软雅黑";
}
.container{
width: 1230px;
margin:0 auto;
}
.gd{
width:100%;
height: 40px;
background-color: pink;
line-height: 40px;
text-align: center;
top: 200px;
display:none;
}
.gddw{
width:100%;
height: 40px;
background-color: pink;
line-height: 40px;
text-align: center;
display:block;
position:fixed;
top: 0;
left:0;
}
.gddw2{
width:100%;
height: 40px;
background-color: pink;
line-height: 40px;
text-align: center;
display:none;
}
.ooo{
width:100%;
height:400px;
background-color: orange;
}
</style>
html代码
<body style="height:3000px">
<div class="allcontainer ">
<div class="container">
<ul class="items">
<li class="item">111</li>
<li class="item">222</li>
<li class="item">333</li>
<li class="item">444</li>
<li class="item">555</li>
</ul>
</div>
<div class="ooo"></div>
<div class="gd">我麻麻咧咧来盘我</div>
</div>
</body>
<script type="text/javascript">
gd = document.getElementsByClassName("gd")[0] 获取元素下标
window.onscroll = function(){ 添加滚动条事件。onscroll
var a = ooo.offsetTop; //offsetTop到顶部的距离
var b = document.documentElement.scrollTop //scrollTop滚动条到顶部的距离
if(b>a){
gd.className = "gddw";
//.className添加一个类名
}
else{
gd.className = "gddw2";
}
}
</script>
</html>
注意:
1、获取元素时要在后面加下标,第一个默认为[0]
2、要注意语法规范
概述:
综合来讲这个版本的吸顶条属于比较简单的一个版本,很容易上手
本文介绍了一种使用CSS和JavaScript实现的简单吸顶效果。通过监听滚动事件,判断元素位置,动态切换元素样式,实现导航栏固定在屏幕顶部的效果。
2268





