当方js初心者です。
IntersectionObserver API
を使用して、「要素が画面内に入ったらclass付与」を実装しようとしています。
仕組みは簡単に実装できましたが、
可能であれば
「閾値(threshold)」を要素ごとに変化させたい
と考えております。
実行したいことの詳細
まず、
IntersectionObserver API を読み込む前に、
optionsを以下のように設定しております。
javascript
1const options = { 2 rootMargin: '0px' 3 threshold: 0.7 4};
そしてhtml側、IntersectionObserver API対象要素には、以下のように記述しております。
html
1<div class="box box02 js-dp" data-threshold="0.5">targetA</div> 2<div class="box box02 js-dp" data-threshold="0.2">targetB</div>
そして私が叶えたい内容が、
「target要素にdata-thresholdがあれば、その要素に関しては、data-thresholdをthreshold値として設定する」
というものです。
以下、現在のjsコード
javascript
1/* 2* 要素がウィンドウ内に入ったらclass付与(IntersectionObserver API) 3* 「js-dp」classを持っている要素に-displayクラスを追加 4*/ 5(function() { 6 const options = { 7 rootMargin: '0px', 8 threshold: 0.7 // デフォルト値 9 }; 10 const observer = new IntersectionObserver(callback, options); 11 12 const targets = document.querySelectorAll('.js-dp'); 13 14 targets.forEach(target => { 15 observer.observe(target); 16 }); 17 18 function callback(entries) { 19 entries.forEach(entry => { 20 21 if(entry.isIntersecting) { 22 entry.target.classList.add('-display'); 23 } 24 }); 25 }; 26})();
この実装はそもそも可能なのか、という点でも疑問に思っております。
言葉足らずな点もあるかと思いますが、どうぞよろしくお願いいたします。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/01/17 05:04