jQuery - 在滚动时更改背景颜色 [英] jQuery - Change background-color on scroll
本文介绍了jQuery - 在滚动时更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在滚动时更改导航栏的 background-color
(当前设置为 transparent
).我尝试了很多不同的东西,但它不起作用.请帮帮我.
I am trying to change the background-color
(currently set at transparent
) of my navbar on scrolling. I have tried lots of different things but it does not work. Please help me.
这是我当前的代码
$(window).ready(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 300) {
$(".navbar").css("background", "blue");
} else {
$(".navbar").css("background", "transparent");
}
})
})
ps.我不认为这可能是原因,但我已经用 Foundation 建立了网站.但是,我使用常规 SCSS 设置了 background: transparent
.
ps. I don't think this can be the cause but I have built the website with Foundation. However, I have set the background: transparent
using regular SCSS.
推荐答案
你必须添加一个类并调用它,查看下面的例子
You have to add a class and call it, Check below example
var navbar = document.querySelector('nav')
window.onscroll = function() {
// pageYOffset or scrollY
if (window.pageYOffset > 100) {
navbar.classList.add('scrolled')
} else {
navbar.classList.remove('scrolled')
}
}
nav {
position: -webkit-sticky;
position: sticky;
position: fixed;
top: 0;
height: 80px;
width: 100%;
background: #ffa5001f;
}
nav.scrolled {
background: orange;
}
main {
height: 200vh;
}
<nav></nav>
<main></main>
这篇关于jQuery - 在滚动时更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文