JS small practice - realize sidebar and sticky positioning effect

<!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>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .left {
            width: 95%;
        }

        .box1,
        .box2,
        .box3 {
            width: 100%;
            height: 500px;
            border: 1px solid gray;
            margin-bottom: 100px;
        }

        .left {
            float: left;
        }

        .box1 {
            background-color: antiquewhite;
        }

        .box2 {
            background-color: aqua;
        }

        .box3 {
            background-color: aquamarine;
        }

        .aside {
           height: 200px;
           width: 100%;
            background-color: blue;
            
        }
        .right{
            position: absolute;
            right: 0px;
            top: 400px; 
            width: 4.7%;
            height: 400px;
        }
        .tu {
            width: 100%;
            height: 100px;
            background-color: gray;
            color: aliceblue;
            display: none;
        }
        .bot{
            height: 100px;
            width: 100%;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="left">
        <div class="box1"></div>
        <div class="box2"></div>
        <div class="box3"></div>
    </div>
    <div class="right">
        <div class="aside"></div>
        <div class="tu">没想到吧</div>
        <div class="bot"></div>
    </div>

    <script>
        let right = document.querySelector(".right")
        let tu=document.querySelector(".tu")
        document.addEventListener("scroll", function () {
            if (window.pageYOffset >= 300) {
                right.style.position = "fixed"
                right.style.top = "100px"
            }
            else {
                right.style.position = "absolute"
                right.style.top = "400px"
            }
            if(window.pageYOffset>=500){
                tu.style.display="block"
            }
            else{
                tu.style.display="none"
            }
        })
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/m0_45293340/article/details/126556247