画面に表示したらアニメーションで表示するjsです。
jqueryなしで、IEにも対応しています。
HTML
<div class="fade_box" data-anitype="fadein-bottom">1</div>
<div class="fade_box" data-anitype="fadein-left">1</div>
<div class="fade_box" data-anitype="fadein-right">1</div>
fade_box
が対象のクラスで、data-anitype
で動きのクラスを設定します。
IE対応をする場合はポリフィルを使用しますので<head>内に
<script src="https://cdn.jsdelivr.net/npm/intersection-observer@0.9.0/intersection-observer.js"></script>
を記入してください。
css
/*アニメーション▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼*/
.fade_box {
transition: 1s ease-in;
width:auto;
height: auto;
opacity:0;
padding: 100px 10px;
margin: 30px;
}
/*下からフォードイン*/
.fadein-bottom {
animation-name: fadeup;
animation-duration: 1s;
animation-fill-mode: forwards;
background: blue;
}
@keyframes fadeup {
0% {
opacity: 0;
transform: translateY(50px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
/*左からフォードイン*/
.fadein-left {
animation-name: fadeleft;
animation-duration: 1s;
animation-fill-mode: forwards;
background: blue;
}
@keyframes fadeleft {
0% {
opacity: 0;
transform: translateX(-70px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
/*右からフェードイン*/
.fadein-right {
animation-name: faderight;
animation-duration: 1s;
animation-fill-mode: forwards;
background: blue;
}
@keyframes faderight {
0% {
opacity: 0;
transform: translateX(70px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
/*アニメーション▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲*/
今回は下からと左右の設定をしています。
応用をすれば色を変えたり回転したりなど色々と動きをつけることが出来ます。
JS
window.onload = function() {
// data-reveal-class 属性が指定されている要素をすべて取得
var elements = document.querySelectorAll('[data-anitype]');
var callback = function (entries, observer) {
// 監視対象で変化があったものすべてが entries に入ってくる
entries.forEach(function(entry){
var target = entry.target;
if (entry.isIntersecting) {
target.classList.add(target.dataset.anitype);
} else {
//通り過ぎた後に再度フェードを入れる時は使用
//target.classList.remove(target.dataset.anitype);
}
});
}
var option = {
root: null,
rootMargin: "0px",
threshold: [0]
};
var observer = new IntersectionObserver(callback, option); // callback, optionを設定
// Polyfillを使っている場合コメントアウトを外す
observer.POLL_INTERVAL = 100;
// すべての要素を監視対象にする
const ele = document.querySelectorAll('[data-anitype]');
const eles = Array.prototype.slice.call(ele); //Array
eles.forEach(function($elm){
observer.observe($elm);
});
};
IntersectionObserver
というAPIを使っています。
これがIE対応していないのでPolyfill
の設定が必要となります。
コメント