其他分享
首页 > 其他分享> > DOM:滚动时固定导航栏

DOM:滚动时固定导航栏

作者:互联网

简单实现滚动时固定导航栏

实例代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    body {
        margin: 0;
    }

    .div1 {
        background-color: aqua;
        width: 200px;
        height: 200px;
        font-size: 30px;
    }

    .div2 {
        background-color: darkcyan;
        width: 200px;
        height: 200px;
        font-size: 30px;
    }

    .div3 {
        background-color: darkgreen;
        width: 200px;
        height: 2000px;
        font-size: 30px;
    }
</style>

<body>

    <div class='div1'>aqua</div>
    <div class='div2'>darkcyan</div>
    <div class='div3'>darkgreen</div>

    <script>
        window.onload = function () {
            document.body.onscroll = function () {
                let pY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop
                var div2 = document.querySelector('.div2')
                var div3 = document.querySelector('.div3')
                if (pY > 200) {
                    div2.style.position = 'fixed'
                    div2.style.top = '0px'
                    div3.style.lineHeight= '2000px';
                } else {
                    div2.style.position = ''
                    div2.style.top = ''
                }
            }
        }

    </script>
</body>

</html>

 

效果图:

滑动前:

 

 

滑动后:

 

标签:style,滚动,DOM,color,div3,document,导航,div2,200px
来源: https://www.cnblogs.com/LIXI-/p/16507860.html