固定右侧侧边栏案例

固定右侧侧边栏案例

案例分析:内容区域分成header区、banner区、main区
1.需要用到页面滚动事件scroll,事件源是document;
2.滚动到某个位置,就是判断页面被卷去的上部值。
3.页面被卷去的头部,可通过window.pageYOffset获得,如果被卷去的是左侧,window.pageXOffset。注意,元素被卷去的头部:可以通过element.scrollTop,页面则是window.pageYOffset
分情况讨论,页面被卷去的长度与元素的offsetTop(距离页面上部的距离)
初始效果
在这里插入图片描述
只要页面滚动,我的元素就会往上滚,卷去头部,只要slider到达banner后(window.pageYOffset>banner.offsetTop),就将侧边栏改为固定定位(这里的页面上边距可以固定一个值,侧边栏的offsetTop-banner.offsetTop),小于时,是固定定位。
另外,当页面到达最下方main时,显示侧边栏的文字。(mian.style.display=‘block’)。其他位置显示none。

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .w {
            margin: 0 auto;
        }
        
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 50px;
            height: 100px;
            background-color: purple;
        }
        
        .header,
        .banner,
        .main {
            width: 1100px;
            height: 100px;
            margin: 10px;
        }
        
        .goback {
            display: none;
        }
        
        .header {
            background-color: pink;
        }
        
        .banner {
            background-color: blue;
        }
        
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class='goback'>返回顶部</span>
    </div>
    <div class="header w">头部</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        //console.log(bannerTop);
        var bannerTop = banner.offsetTop //被卷曲头部
        console.log(sliderbar.offsetTop);
        console.log(bannerTop);
        console.log(sliderbarTop);

        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        var main = document.querySelector('.main');
        var goback = document.querySelector('.goback');

        document.addEventListener('scroll', function() {

            if (window.pageYOffset >= bannerTop) { //页面被卷去头部
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop + 'px';
            } else {
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = '300px';
            }
            if (window.pageYOffset >= main.offsetTop) {
                goback.style.display = 'block';
                console.log(main.offset);
            } else {
                goback.style.display = 'none';
            }
        })
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/ljyahaha/article/details/109394071
今日推荐