我只能訪問 h1 中的第一個元素。我還可以創建一個按鈕并單擊回圈遍歷 h1 元素并打開或關閉 .textDecoration 類。但我的目標是一步一步單擊我想要的元素并打開或關閉 .textDecoration 類。
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>
uj5u.com熱心網友回復:
我建議你委托
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>
uj5u.com熱心網友回復:
你的問題在我看來很糟糕,你在找那個嗎?
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404696.html
標籤:
上一篇:在螢屏頂部添加3個徽標
