滚动条开始滚动时,左侧导航固定,当左侧内容触底到footer时左侧内容取消固定并跟随滚动条滚动

发布于:2025-08-11 ⋅ 阅读:(20) ⋅ 点赞:(0)

页面上当滚动条滚动时,需要左侧内容固定不动,但是当内容触底到footer时,我们不希望左侧内容压在footer上,视觉上不好看,这时候需要左侧内容取消固定,滚动条在这个范围滚动时,需要左侧内容一直出现在footer上方,直到滚动条滚动超出footer范围,左侧导航继续固定不动。

计算方法:

第一步:计算左侧导航高度,给左侧导航设置fixed属性

第二步:根据(文档的总高度 - 文档内部可见区域的高度 - 元素顶部不可见部分的高度),获取到的高度如果大于footer的总高度,就去除fixed属性,设置absolute属性

        <div class="header bg">header</div>
        <div class="wrapper">
            <div class="left-box">
                <div id="left-id" class="bgleft scrollfixed">
                    左侧内容
                </div>
            </div>
            <div class="content-box bg">
                content主要内容
            </div>
        </div>
        <div class="page-footer bg">
            footer
        </div>
       .header{
            height: 100px;
            margin-bottom: 20px;
        }
        .wrapper{
            display: flex;
        }
        .bg{
            background-color: #2d343c;
            padding: 20px;
            border-radius: 5px;
            color: #fff;
        }
        .bgleft{
            background-color: #29ad9b;
            padding: 20px;
            border-radius: 5px;
            color: #fff;
        }
        .left-box{
            width: 240px;
            position: relative;
        }
        .scrollfixed{
            position: fixed;
        }
        #left-id{
            width: 200px;
            height: 600px;
        }
        .content-box{
            height: 2000px;
            margin: 0 20px;
            flex: 1;
        }
        .right-box{
            width: 200px;
            height: 300px;
        }
        .page-footer{
            margin: 20px 0;
            height: 400px;
        }
        .scrollabsolute{
            position: absolute;
            bottom: 0;
        }
window.addEventListener('scroll', function(){
                const targetTop = $('#left-id').offset().top;
                const targetBottom = targetTop + $('#left-id').height();
                const containerTop = $('.page-footer').offset().top;
                const containerBottom = containerTop - $('.page-footer').height();
                if (targetBottom - containerTop > 0) {
                    $('#left-id').addClass("scrollabsolute");
                } 
                const element = document.documentElement; // 获取html文档
                const scrollHeight = element.scrollHeight; // 文档的总高度
                const clientHeight = element.clientHeight; // 文档内部可见区域的高度
                const scrollTop = element.scrollTop; // 元素顶部不可见部分的高度
                // 计算剩余滚动条距离
                const remainingScroll = scrollHeight - clientHeight - scrollTop;
                if(remainingScroll > 440){
                    $('#left-id').removeClass("scrollabsolute")
                }
            });


网站公告

今日签到

点亮在社区的每一天
去签到