html - 整页标题后的固定侧边栏

标签 html css

对于我的网站,我实现了一个固定的侧边栏:

我的问题是,如果我将侧边栏 position 设置为 fixed,那么我的侧边栏也会出现在整页页眉的前面。我希望我的侧边栏在标题之后开始,就好像我已经将它的 position 设置为 absolutetop: 100vh 一样,除了它会保留当我向下滚动时修复。

您如何实现这一目标?非常感谢您!

body {
  margin:0;
}

#header {
  height: 100vh;
  width:100%;
  position:relative;
  background-color:blue;
}


#main {
        margin-left: 20vw;
        height: 100vh;
    }
    
    sidebar {
        width: 20vw;
        height: 100vh;
        top: 0;
        left: 0;
        background-color: #130E0A;
        position: fixed;
        z-index: 1;
    }
<!DOCTYPE html>
    <html>
        <head>
    		<title>Etude de controverse : Le théorème des 4 couleurs et les preuves informatiques</title>
            <meta name='viewport' content='initial-scale=1.0'>
            <meta charset='utf-8'>
        </head>
        <body>
    		<section id='header'></section>
    
            <section id='main'>
                <sidebar></sidebar>
                <div id='timeline' class='cd-container'></div>
            </section>
        </body>
    </html>

最佳答案

如果你会使用 jQuery,你就可以使用类似的东西。

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

     //>=, not <=
    if (scroll >= 1000) {
        //clearHeader, not clearheader - caps H
        $("sidebar").addClass("fixed");
    }
    else {
      $("sidebar").removeClass("fixed");
    }
}); //missing );
body {
  margin:0;
}

#header {
  width:100%;
  background-color:blue;
   height: 1000px;
}


#main {
        margin-left: 20vw;
        height:10000px;
    }
    
    sidebar {
        width: 20vw;
        height: 500px;
        display:block;
        background-color: #130E0A;
        position: relative;
        z-index: 1;
    }
    
    sidebar.fixed {
      position:fixed;
      left:20vw;
      top:0;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
    <html>
        <head>
    		<title>Etude de controverse : Le théorème des 4 couleurs et les preuves informatiques</title>
            <meta name='viewport' content='initial-scale=1.0'>
            <meta charset='utf-8'>
        </head>
        <body>
    		<section id='header'></section>
    
            <section id='main'>
                <sidebar></sidebar>
                <div id='timeline' class='cd-container'></div>
            </section>
        </body>
    </html>

关于html - 整页标题后的固定侧边栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43662098/

相关文章:

javascript - 有没有办法使用 jQuery 和/或 CSS 通过单击按钮来反转页面上的所有颜色?

css - 将html转换为pdf时如何防止文本溢出(并填充div)?

jquery - 如何对 svg 过滤器 feComponentTransfer 进行动画处理?

javascript - 在 d3.js 元素中添加 slider

html - 无法根据屏幕分辨率应用样式表

html - 将属性更改为元素子项

html - CSS float 和 block 元素

html - 防止包含图像的 li 元素溢出

php - codeigniter fatal error ,试图读取数据库

javascript - jQuery 在元素动画之后滚动到元素