问题
I would like the navigation bar to be transparent but when you scroll down the page it changes to color red for example.
<div class="nav">
<div class="container">
<div class="logo">
<a href="#"><img src="RepublicSquare_logo.svg" style="height: 80px;"></a>
</div>
<div class="navMain">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
</div>
回答1:
Something like this:
http://jsfiddle.net/qrhjdfmd/
var a = $(".nav").offset().top;
$(document).scroll(function(){
if($(this).scrollTop() > a)
{
$('.nav').css({"background":"red"});
} else {
$('.nav').css({"background":"transparent"});
}
});
回答2:
If anyone would be looking for a non-jquery solution (vanilla js), here it is:
document.addEventListener("DOMContentLoaded", function () {
var scrollStart = 0;
var nav = document.querySelector(".nav");
var offset = navbarElement.getBoundingClientRect();
document.onscroll = function (e) {
scrollStart = e.target.scrollingElement.scrollTop;
if (scrollStart > offset.top) {
nav.style.background-color, rgba(34,34,34,0.9);
} else {
nav.style.background-color = "transparent";
}
};
});
回答3:
Solution by OP.
Jquery
$(document).ready(function(){
var scroll_start = 0;
var startchange = $('.nav');
var offset = startchange.offset();
$(document).scroll(function() {
scroll_start = $(this).scrollTop();
if(scroll_start > offset.top) {
$('.nav').css('background-color', 'rgba(34,34,34,0.9)');
} else {
$('.nav').css('background-color', 'transparent');
}
});
});
CSS
.nav {
transition-duration: 1s;
}
This should make your navigation transparent and when you scroll it will change to rgba(34,34,34,0.9)
来源:https://stackoverflow.com/questions/27308425/how-to-make-navigation-bar-change-color-when-you-scroll-down-the-page