前提
下記のHTMLソースがあったとします。
<html> <header id="foo"></header> <div id="baa"></div> <div id="hogehoge"></div> </html>
javascriptソースコード
java
1<script> 2 window.addEventListener("scroll", function () { 3 if (window.innerWidth <= 767) { 4 const foo = document.querySelector("#foo"); 5 foo.classList.toggle("hoge", window.scrollY > 100); 6 const baa = document.querySelector("#baa"); 7 baa.classList.toggle("hoge", window.scrollY > 100); 8 const hogehoge = document.querySelector("#hogehoge"); 9 hogehoge.classList.toggle("hoge", window.scrollY > 100); 10 } 11 }); 12</script>
実現したいこと
現状のjavascriptでも正常に動いてはいるのですが、同じ条件下で同じクラスを付けているため、もう少しソースがコンパクトにできないかと悩んでいます。
const all = document.querySelector("#foo, #baa, #hogehoge");
や
const all = document.querySelectorAll("#foo, #baa, #hogehoge");
などを試しましたが、うまく全てのIDにクラスが付いてくれませんでした。
どのようにすればコンパクトにできるでしょうか。
また、今回の条件ではコンパクトにはできないでしょうか。
初心者なため、これ以上はどうすることもできなかったため、お力を貸して頂ければと思います。
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー