スクロールによって、ヘッダーの色が変わるやつを書いてみました。
Demo - codepen
html
1<head>
2 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
3</head>
4
5<body>
6 <div>
7 <header class="header">logo</header>
8 <div style="margin-top:48px;">
9 <div id="section1">First View</div>
10 <div id="section2">Second View</div>
11 <div id="section3">Third View</div>
12 </div>
13 </div>
14</body>
css
1body {
2 margin: 0;
3 padding: 0;
4}
5
6.header {
7 background-color: #333;
8 color: #fff;
9 text-align: center;
10 line-height: 48px;
11 width: 100%;
12 position: fixed;
13 top: 0;
14 transition: background-color .2s, color .2s
15}
16
17.header--scrolled {
18 background-color: rgba(255,255,255,.8);
19 color: #333;
20}
21
22#section1,
23#section2,
24#section3{
25 margin: 0;
26 padding: 0;
27 text-align: center;
28 height: 100vh;
29 width: 100vw;
30}
31
32#section1,
33#section3{
34 background: #ddd;
35}
36#section2 {
37 background: #555;
38}
js
1$(window).scroll(function () {
2 var scrollTop = $(window).scrollTop();
3 if( 200 < scrollTop && scrollTop < 1200 ){
4 $('.header').addClass('header--scrolled');
5 }else{
6 $('.header').removeClass('header--scrolled');
7 }
8});
以下追記
jQueryのaddClass()
removeClass()
メソッドを使用して .header--scrolled
をつけたり外したりして色を変えていますが、 css()
メソッドを使用して
js
1$(window).scroll(function () {
2 var scrollTop = $(window).scrollTop();
3 if( 200 < scrollTop && scrollTop < 1200 ){
4 $('.header').css('background-color','rgba(255,255,255,.8)');
5 }else{
6 $('.header').css('background-color','#333');
7 }
8});
とかでもいけます!