ページをスクロールして画像が表示される位置になると、徐々に表示されるアニメーション作ります。
◆まずはデモページをご覧ください。
デモページを見る
◆HTMLです。
最初の「container」が左から右へ徐々に表示され、次の「container」は逆に右から左へ徐々に表示されます。
HTML
<div class="container">
<div class="move_img l_to_r">
<img src="img/image.jpg" alt="">
</div>
</div>
<div class="container">
<div class="move_img r_to_l">
<img src="img/image.jpg" alt="">
</div>
</div>
◆CSSです。
CSS
.move_img {
position: relative;
overflow: hidden;
height: auto;
opacity: 0;
}
/* 左から右へ表示される */
.move_l_to_r::before{
position: absolute;
content: '';
left: 0;
top: 0;
bottom: 0;
right: 0;
background: #fff;
animation: move_animation_r 0.8s linear 0s 1 forwards normal;
}
@keyframes move_animation_r {
100% {
transform: translateX(100%);
}
}
/* 右から左へ表示される */
.move_r_to_l::before{
position: absolute;
content: '';
left: 0;
top: 0;
bottom: 0;
right: 0;
background: #fff;
animation: move_animation_l 0.8s linear 0s 1 forwards normal;
}
@keyframes move_animation_l {
100% {
transform: translateX(-100%);
}
}
◆JavaScirptです。「jquery」ファイルも用意しておいてください。
JavaScirpt
$(window).on('scroll', function (){
// .l_to_rクラスがつけられている要素
var elem = $('.l_to_r');
elem.each(function () {
var elemTop = $(this).offset().top;
var scroll = $(window).scrollTop();
var wh = $(window).height();
//要素の上部が画面の中央にきたら
if(scroll > elemTop - wh + (wh / 4) )
{
// .move_l_to_rをつける
$(this).addClass('move_l_to_r');
$(this).css('opacity','1');
}
});
});
$(window).on('scroll', function (){
// .r_to_lクラスがつけられている要素
var elem = $('.r_to_l');
elem.each(function () {
var elemTop = $(this).offset().top;
var scroll = $(window).scrollTop();
var wh = $(window).height();
//要素の上部が画面の中央にきたら
if(scroll > elemTop - wh + (wh / 4) )
{
// .move_r_to_lをつける
$(this).addClass('move_r_to_l');
$(this).css('opacity','1');
}
});
});
CSSの「animation」の記述について、1行で指定した書き方になっているので、細かく解説します。
animation-name
「@keyframes」の名前になります。
「move_animation_r」の部分で、名前は自由に決められます。
animation-duration
アニメーションにかかる時間です。
「0.8s」の部分で、「1s」だと1秒です。
animation-timing-function
アニメーションの動きや速度を指定します。
「linear」の部分で、これは等しい速度でアニメーションする指定になります。
他に、「ease」はゆっくり動いてゆっくり止まる指定です。
animation-delay
アニメーションを何秒後に開始するか指定します。
「0s」の部分で、「1s」だと1秒後に開始します。
animation-iteration-count
アニメーションの再生回数を指定します。
「1」の部分で、これは1回だけ再生します。
animation-fill-mode
アニメーションの再生前後のスタイルを指定します。
「forwards」の部分で、これは再生後も「@keyframes(100%)」が適用されたままになります。
animation-direction
アニメーションの再生方向を指定します。
「normal」の部分で、通常方向をです。
「reverse」だと逆方向になります。