Js吸顶条

本文介绍了一种使用CSS和JavaScript实现的简单吸顶效果。通过监听滚动事件,判断元素位置,动态切换元素样式,实现导航栏固定在屏幕顶部的效果。

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、要注意语法规范

概述:
综合来讲这个版本的吸顶条属于比较简单的一个版本,很容易上手

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值