[英]how to change the color of the navbar after scrolling
I want my navbar to be transparent, but when the user scrolls a bit I want it to change to a solid color and I am using bootstrap for the navbar, I have done the code that is needed with javascript. 我希望导航栏是透明的,但是当用户滚动一点时,我希望它更改为纯色,并且我在导航栏中使用引导程序,因此我已经完成了javascript所需的代码。
I had this javascript in my HTML file, but it doesn't seems to work and I don't really know why 我的HTML文件中有这个javascript,但它似乎不起作用,我也不知道为什么
<script>
var myNav = document.getElementById("mynav");
window.onscroll = function() {
use strict";
if (document.body.scrollTop >= 100) {
myNav.classList.add("scroll");
} else {
myNav.classList.remove("scroll");
}
};
</script>
and I have also added the CSS code. 并且我还添加了CSS代码。
.scroll {
background-color: transparent !important;
transition: all 0.5s ease-in;
}
I don't know why it doesn't work, it is not displaying any errors, I have also manually put the class and it worked so the problem is from the js code and not the CSS. 我不知道为什么它不起作用,它没有显示任何错误,我也手动放置了该类并且它起作用了,所以问题出在js代码而不是CSS。
Use scrollY
property of Window object. 使用Window对象的
scrollY
属性。
See the Snippet below: 请参见下面的代码段:
var myNav = document.getElementById("mynav"); window.onscroll = function() { if (window.scrollY >= 100) { myNav.classList.add("scroll"); } else { myNav.classList.remove("scroll"); } };
.scroll { background-color: transparent !important; transition: all 0.5s ease-in; } .main-container{ height: 1000px; } #mynav{ position: fixed; background-color: gray; height: 50px; margin:0 auto; top: 0; bottom:0; line-height: 50px; padding:5px; width: 100%; }
<div class="main-container"> <div class="mynav" id="mynav"> Hello World! this is mynav </div> </div>
Try using window.scrollY
instead of document.body.scrollTop
. 尝试使用
window.scrollY
而不是document.body.scrollTop
。
if (window.scrollY >= 100)
You can also use document.documentElement.scrollTop
. 您还可以使用
document.documentElement.scrollTop
。 It's the html element that actually scrolls, not the body. 实际上滚动的是html元素,而不是正文。 Typically
document.body.scrollTop
will always be 0. 通常,
document.body.scrollTop
始终为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.