固定栏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;padding: 0;list-style: none;
        }
        .green{
            width: 100%;
            height: 150px;
            background: green;
        }
        .red {
            width: 100%;
            height: 50px;
            background: red;
        }
        body{
            overflow: scroll;
            overflow-x: hidden;
            height: 3000px;
            /*position: fixed;*/
        }

    </style>
</head>
<body>
    <div class="green"></div>
    <div class="red"></div>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
    </ul>
<script>
    window.onscroll=function(){
        var red=document.getElementsByClassName("red")[0];
        if(document.documentElement.scrollTop>150){
           red.style.position="fixed";
            red.style.top="0px";
        }
        if(document.documentElement.scrollTop<150){
            red.style.position="";
        }
    }

</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/moonlight201868/article/details/80893215
今日推荐