几行CSS和JS代码实现粘性元素固定并监听何时固定

<!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>Sticky</title>
    <style>
        html, body {
            margin: 0;
            padding: 0;
        }

        .block {
            height: 100px;
        }

        #parent {
            height: 2000px;
        }

        .myElement {
            position: sticky;
            top: -1px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: skyblue;
            color: snow;
        }

        /* styles for when the header is in sticky mode */
        .myElement.is-pinned {
            color: red;
        }
    </style>
</head>

<body>
    <div id="parent">
        <div class="block"></div>
        <div class="myElement">Tittle</div>

    </div>
</body>
<script>
    const el = document.querySelector(".myElement")
    const observer = new IntersectionObserver(
        ([e]) => e.target.classList.toggle("is-pinned", e.intersectionRatio < 1), {
            threshold: [1]
        }
    );

    observer.observe(el);
</script>

</html>

 

 

posted @ 2022-01-14 10:47  一路向北√  阅读(157)  评论(0编辑  收藏  举报

web应用开发&研究 -

业精于勤而荒于嬉。

工作,使我快乐。


Font Awesome | Respond.js | Bootstrap中文网