ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

利用scroll实现侧边栏固定

2021-04-09 23:01:39  阅读:22  来源: 互联网

标签:style color goBack goHeader 侧边 height 固定 var scroll


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        a{
            color: #333;
            text-decoration: none;
        }
        body{
            height: 2000px;
        }
        .w{
            width: 1200px;
            margin: 10px auto;
        }
        .header{
            height: 150px;
            background-color: lightblue;
        }
        .banner{
            height: 300px;
            margin-bottom: 10px;
            background-color: skyblue;
        }
        .main{
            height: 800px;
            background-color: #1d75b3;
        }
        .slider-bar{
            position: absolute;
            left: 50%;
            top: 260px;
            width: 40px;
            height: 100px;
            margin-left: 600px;
            background-color: pink;
        }
        .goBack{
            display: none;
            position: absolute;
            bottom: 0;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="slider-bar">
    <a href="#" class="goBack">返回顶部</a>
</div>
<div class="header w">头部区域</div>
<div class="banner w">banner区域</div>
<div class="main w">主体部分</div>

<script>
    var goHeader=document.querySelector('.slider-bar');
    var goBack=document.querySelector('.goBack');
    var banner=document.querySelector('.banner');
    var main=document.querySelector('.main');
    var mainTop=main.offsetTop;
    var bannerTop=banner.offsetTop;
    var sliderTop=goHeader.offsetTop-bannerTop;
    console.log(sliderTop);
    document.addEventListener('scroll',function (){
        if( window.pageYOffset>=bannerTop){
            goHeader.style.position='fixed';
            goHeader.style.top=sliderTop+'px';
        }else{
            goHeader.style.position='absolute';
            goHeader.style.top=260+'px';
        }
        if (window.pageYOffset>=mainTop){
            goBack.style.display='block';
        }else{
            goBack.style.display='none';
        }
    })
</script>
</body>
</html>

标签:style,color,goBack,goHeader,侧边,height,固定,var,scroll
来源: https://blog.csdn.net/m0_49007778/article/details/115561096

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有