コンテンツが可視範囲に入ると、ふわっと浮かんでくるスクロールエフェクトを作ってみました。
↓以下が実際のソースサンプルです。
▼JavaScript
<script>
$(function(){
$(".effect div,.effect img").css("opacity","0");
$(window).scroll(function (){
$(".effect").each(function(){
var imgPos = $(this).offset().top;
var scroll = $(window).scrollTop();
var windowHeight = $(window).height();
if (scroll > imgPos - windowHeight + windowHeight/5){
$("div,img",this).css("opacity","1" );
$("img",this).css({
"margin-top": "0px"
});
}
else {
$("div,img",this).css("opacity","0" );
$("img",this).css({
"margin-top": "30px"
});
}
});
});
});
</script>
▼CSS
<style>
html, body {
height: 100%;
}
body {
margin: 0;
color: #23001E;
}
section {
width: 100%;
height: 100%;
text-align: center;
position: relative;
}
h2{
width: 200px;
border: 1px solid #23001E;
padding: 10px;
}
p {
width: 200px;
padding: 10px;
}
.fixed {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 200px;
height: 200px;
}
.absolute {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 200px;
height: 100px;
}
img {
margin-left: -50px;
margin-top: 30px;
}
#section1 {
background-color: #BCB382;
}
#section2 {
background-color: #A4A9AD;
}
#section3 {
background-color: #F6E27F;
}
#section3 .absolute {
height: 400px;
}
.effect div {
margin: auto;
transition: 1s;
}
.effect img {
transition: 1s;
transition-delay: 1s;
}
</style>
▼HTML
<section id="section1"> <div class="fixed"> <h2>Section1</h2> <p>スクロールするとテキストがふわっと現れます。</p> </div> </section> <section id="section2"> <div class="absolute effect"> <div> <h2>Section2</h2> </div> </div> </section> <section id="section3"> <div class="absolute effect"> <div> <h2>Section3</h2> <p>少し下から画像がふわっと現れます。</p> </div> <img src="cat.jpg" alt="ねこ"> </div> </section>
今回、参考にさせていただいたのは、
『jQueryとCSSのtransitionで可視範囲に入ってからアニメーションさせる方法|Webpark』さんです。
ありがとうございます。
