JSFiddle - React, Tailwind, and code Playground
by kachibito
HTML
<div id="wrap">
<div id="article">
<div class="section">
<h2>Section0</h2>
<p>ここは0番目のコンテンツです。</p>
</div>
<div class="section">
<h2>Section1</h2>
<p>ここは1番目のコンテンツです。</p>
</div>
<div class="section">
<h2>Section2</h2>
<p>ここは2番目のコンテンツです。</p>
</div>
<div class="section">
<h2>Section3</h2>
<p>ここは3番目のコンテンツです。</p>
</div>
<div class="section">
<h2>Section4</h2>
<p>ここは4番目のコンテンツです。</p>
</div>
<!-- /#article --></div>
<ul id="nav">
<li><a href="#s0">SECTION 0</a></li>
<li><a href="#s1">SECTION 1</a></li>
<li><a href="#s2">SECTION 2</a></li>
<li><a href="#s3">SECTION 3</a></li>
<li><a href="#s4">SECTION 4</a></li>
</ul>
<!-- /#wrap --></div>
CSS
#wrap {
padding-bottom: 10px;
}
#header {
margin-bottom: 30px;
}
h1 a:hover {
text-decoration: underline;
}
#article {
width: 300px;
margin: 0 auto;
}
div.section {
background: #fff;
padding: 20px;
height: 1000px;
margin-bottom: 20px;
}
#nav {
z-index: 1;
top: 100px;
left: 20px;
position: fixed;
background: #fff;
list-style: none;
}
#nav li a {
text-decoration: none;
width: 140px;
display: block;
padding: 5px;
text-align: center;
}
#nav li a:hover {
background: #E3E3E3;
}
#bg0, #bg1, #bg2, #bg3, #bg4 {
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
#bg0 {
background: #000;
}
#bg1 {
background: #eee;
}
#bg2 {
background: #555;
}
#bg3 {
background: #ccc;
}
#bg4 {
background: #999;
}
JavaScript
$(function() {
var secTopArr = new Array();
var moveFlug = false;
var allHeight = $('body').outerHeight(true);
var bgImg = new Array('#000','#eee', '#555', '#ccc', '#999');
$('div.section').each(function (i) {
secTopArr[i] = $(this).offset().top;
});
var current = -1;
$(window).scroll(function () {
for (var i = secTopArr.length-1; i>=0; i--) {
if ($(window).scrollTop() > secTopArr[i] - 100) {
chengeBG(i);
break;
}
}
});
//背景変更
function chengeBG(secNum) {
if (secNum != current && moveFlug == false) {
$('#bg'+current)
.fadeOut(500, function(){
$(this).remove();
});
$('#wrap').append('<div id="bg'+secNum+'"></div>');
$('#bg'+secNum)
.height(allHeight)
.css('display','none')
.fadeIn(500);
current = secNum;
}
}
$('#nav li').click(function(){
moveFlug = true;
var getNum = $(this).index();
var secTop = $('.section').eq(getNum).offset().top;
$('html,body').animate({ scrollTop: secTop }, 'slow', function() {
moveFlug = false;
chengeBG(getNum);
});
return false;
});
});