吸顶js/css

20行js = 2行css, css yyds!!!

以下两篇搞懂原理

彻底理解粘性定位 - position: sticky - 简书

​​​​​​搞清clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop_飞歌Fly的博客-优快云博客_offsetheight​​​​​​

0.需求,使大红色框在滚动到顶部后,固定到顶部

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 100%;
            height: 100px;
            margin-bottom: 15px;
            background-color: pink;
        }
        
        #red {
            background-color: red;
        }
        body {
            height: 3000px;
        }
    </style>
</head>
<body>

  <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div id="red"></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>

</html>

 

1.使用css

    直接给#red添加属性position:sticky;  top:0;

        #red {
            background-color: red;
            position:sticky;
            top:0;
        }

2.使用js

css 不变,依旧是 0.需求中的样式,添加js

<script>
    //逻辑
    var oDiv = document.getElementById("red");
    //div在页面的占位高,div到body的距离
    var otop = oDiv.offsetTop;
    console.log('otop', otop)
    //页面滚动
    window.onscroll = function () {
        //获取页面的滚动距离
        var oheight = document.documentElement.scrollTop || document.body.scrollTop;
        console.log('oheight', oheight)
        //滚动到一定位置 div固定到顶部 js实现吸顶
        if (otop < oheight) {
            oDiv.style.position = "fixed";
            oDiv.style.top = 0;
        } else {
            oDiv.style.position = "relative";
        }
    }
</script>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值