簡體   English   中英

當我單擊“全部”h1 元素時,我想切換。textDecoration class。 你能幫我看看這個守則嗎?

[英]I want to toggle .textDecoration class when I am clicking on "ALL" h1 elements. Can you Help me with this Code?

我只能訪問 h1 中的第一個元素。 我還可以創建一個按鈕並單擊循環遍歷 h1 元素並打開或關閉。textDecoration class。 但我的目標是一步一步單擊我想要的元素並打開或關閉。textDecoration class。

 var x = document.getElementsByTagName("h1")[0]; function myFunction() { x.classList.toggle("textDecoration"); } x.addEventListener("click", myFunction);
 .textDecoration { text-decoration: line-through; }
 <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1>

我建議你委托

 document.getElementById("container").addEventListener("click", function(e) { const tgt = e.target.closest("h1"); if (tgt) tgt.classList.toggle("textDecoration"); })
 .textDecoration { text-decoration: line-through; }
 <div id="container"> <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1> </div>

在我看來,您的問題表述得很糟糕,您在尋找嗎?

 document.querySelectorAll('h1').forEach( (Hn,_,All_h1) => { Hn.onclick =_=> { if (Hn.classList.toggle('textDecoration')) All_h1.forEach( Hx=> Hx.classList.toggle('textDecoration', Hn===Hx) ) } })
 .textDecoration { text-decoration: line-through; }
 <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1> <h1>Text-Decoration: line-through</h1>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM