以下が記載されています。
このファイルの読み込みの後にmain.jsを読み込んで、その中に「上記クラスを使った監視の書き方 例2)」のようなコードを記述してください。
class ScrollObserver {
constructor(els, cb, options) {
//constructorの中に記述するものは、基本的にプロパティに値を設定するものに限定する。
//関数はプライベートメソッドに入れて、constructorの最後に初期化処理を施すことで、定義漏れやバグを防ぐことができる。
this.els = document.querySelectorAll(els);
this.cb = cb;
const defaultOptions = {
root: null,
rootMargin: "0px",
threshold: 0,
once: true,
};
//第三引数のoptionsとdefaultOptionsをマージする(仮引数とconstructor内に記述したものをイコールにしたい。だけど直接仮引数をセットできない時に)
this.options = Object.assign(defaultOptions, options);
this.once = this.options.once;
this._init();
}
_init() {
const callback = function (entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.cb(entry.target, true); //true = entry.isIntersecting
if (this.once) {
observer.unobserve(entry.target);
}
} else {
this.cb(entry.target, false);
}
});
};
this.io = new IntersectionObserver(callback.bind(this), this.options);
//100ミリ秒ごとにスクロールの値を監視する@polyfill
// @see <https://github.com/w3c/IntersectionObserver/tree/master/polyfill>
this.io.POLL_INTERVAL = 100;
this.els.forEach(el => this.io.observe(el));
}
destroy() {
this.io.disconnect();
}
}
/**
* 上記クラスを使った監視の書き方 例1) @main.js
* document.addEventListener('DOMContentLoaded', function () {
* const cb = (el, isIntersecting) => {
* if (isIntersecting) {
* const ta = new TextAnimation(el);
* ta.animate();
* }
* }
*
* const so = new ScrollObserver('.animate-title', cb);
* so.destroy();
* });
*
*
* 上記クラスを使った監視の書き方 例2) @main.js
* document.addEventListener('DOMContentLoaded', function () {
* ↓任意の関数
* const cb = function (el, isIntersecting) {
* if(isIntersecting) {
* el.classList.add('inview');
* } else {
* el.classList.remove('inview');
* }
* }
* ↓引数には左から順に”監視したい要素”・”監視対象に行いたい関数”・”関数は1回だけ実行か否か”
* const so = new ScrollObserver('.cover-slide', cb, {once: false});
* });
*
*/