The method .offset()
, returns an object containing the properties top
and left
:
{top: 1808, left: 8}
Therefore you need to access the top
property in your conditional statements.
Change
if ($window.scrollTop() >= project1) { ... }
to:
if ($window.scrollTop() >= project1.top) { ... }
Updated Example
As a side note, $('section:nth-child(1)').offset()
will be undefined because the section element isn't the first element (the <header>
is). Use :nth-of-type
rather than :nth-child
. Since you're using jQuery, eq()
would work too.
$(document).ready(function() {
var project1 = $('section:nth-of-type(1)').offset();
var project2 = $('section:nth-of-type(2)').offset();
var project3 = $('section:nth-of-type(3)').offset();
var project4 = $('section:nth-of-type(4)').offset();
var project5 = $('section:nth-of-type(5)').offset();
var project6 = $('section:nth-of-type(6)').offset();
var $window = $(window);
$window.scroll(function() {
if ( $window.scrollTop() >= project1.top) {
$("header").removeClass().addClass("project1");
}
if ( $window.scrollTop() >= project2.top ) {
$("header").removeClass().addClass("project2");
}
if ( $window.scrollTop() >= project3.top ) {
$("header").removeClass().addClass("project3");
}
if ( $window.scrollTop() >= project4.top ) {
$("header").removeClass().addClass("project4");
}
if ( $window.scrollTop() >= project5.top ) {
$("header").removeClass().addClass("project5");
}
if ( $window.scrollTop() >= project6.top ) {
$("header").removeClass().addClass("project6");
}
});
});
header {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 100px;
background: #000;
}
header.project1 {
background: red;
}
header.project2 {
background: orange;
}
header.project3 {
background: blue;
}
header.project4 {
background: green;
}
header.project5 {
background: red;
}
header.project6 {
background: blue;
}
section {
height: 900px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header></header>
<section>Section 1</section>
<section>Section 2</section>
<section>Section 3</section>
<section>Section 4</section>
<section>Section 5</section>
<section>Section 6</section>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…