使用Js固定滚动条上的侧边栏

时间:2020-04-08 11:45:32

标签: javascript css sidebar

我花了数小时试图弄清楚为什么我似乎无法用javscript将侧边栏固定在滚动条上。 在这一点上,我不知道它是在js还是css中。我试图添加一个“ fixed”的classList-没有用..当我添加粘性时,它只是按下了主文本。 这个想法是,一旦用户滚动了整个标题,导航栏和侧边栏便会被固定,但是在固定其他两个元素的同时,滚动主文本。

code here -> https://codepen.io/mullerz/pen/GRpKQVy```
help please and thanks a million

2 个答案:

答案 0 :(得分:0)

CSS position: sticky是唯一需要的东西。您已经在导航中的某个地方使用过它,但是由于使用了JavaScript代码,所以事情变得一团糟。注释掉您的fixNav函数并滚动事件监听器。

请改为使用CSS来说明nav#sidebar元素应何时粘滞。边栏元素应略微偏移,因为它应位于导航栏的正下方。使用top属性,可以设置元素变粘时的触发位置。 leftrightbottom也是如此。

将以下几行添加到您现有的nav#sidebar样式中,看看会发生什么。

nav {
  position: sticky;
  top: 0;
}

#sidebar{
  position:sticky;
  top: 8vh; /* <-- height of the nav */
}

答案 1 :(得分:0)

https://codepen.io/casa90/pen/ZEbzxZB

作为CSS尝试下面。我使用过重要命令是因为您的#sidebar css在它下面。css的顺序很重要。

.fixed-sidebar{
        position:fixed !important;
    }

作为脚本,我计算了导航栏偏移高度,并且将填充从上到下更改了。对于绝对样式或固定样式,您应该使用左上右下。尝试以下

const nav = document.querySelector("#main");
const navTop = nav.offsetTop;
const navHeight = nav.offsetHeight;
const main = document.querySelector(".site-wrap");
const bars = document.querySelector("#bars");
const sidebar = document.getElementById("sidebar");
window.addEventListener("scroll", fixNav )  
function fixNav(){
    sidebar.style.top = (nav.offsetTop+navHeight) + "px";
    if(window.scrollY >= navTop){               
            nav.classList.add("fixed");
            main.style.paddingTop = navHeight + "px";
            sidebar.classList.add("fixed-sidebar");

    }else{
            main.style.paddingTop = 0;
              nav.classList.remove("fixed");
            sidebar.classList.remove("fixed-sidebar");
    }
}

bars.addEventListener("click", function(){  
    sidebar.classList.toggle("active");
})
相关问题