簡體   English   中英

如何打開和關閉

[英]how to toggle on and off

我正在測試一些 JS,想知道如何切換背景顏色更改,然后將顏色更改切換回正常狀態。

謝謝!

 function myFunk() { var y = document.querySelectorAll("h1"); for (var i = 0; i < y.length; i++) { y[1].style.backgroundColor = "blue"; y[2].style.backgroundColor = "red"; } }
 <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <button onclick="myFunk()">push me</button>

最有效的解決方案是簡單地toggle class。 此外,如果您手動引用數組中的 object,則不需要循環

 function myFunk(){ var y = document.querySelectorAll("h1"); y[1].classList.toggle("red"); y[2].classList.toggle("blue"); }
 .red{background-color:red;}.blue{background-color:blue;}
 <html> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <button onclick="myFunk()">push me</button> </html>

請參閱下面的內聯評論:

 // Do your event binding in JavaScript, not HTML document.querySelector("button[type='button']").addEventListener("click", myFunk); function myFunk(){ var y = document.querySelectorAll("h1"); // No need for a loop if you are just targeting specific elements // Use the.toggle() method of the.classList property and work // with pre-made classes instead of inline styles y[1].classList.toggle("red"); y[2].classList.toggle("blue"); }
 .blue { background-color:blue; }.red { background-color:red; }
 <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <button type="button">push me</button>

您可以存儲紅色的索引並將其他 colors 替換為藍色。

這種方法使用一個全局變量index來存儲實際突出顯示的元素的索引。

訪問所有元素,如果活動索引的索引等於具有相同索引的元素,則顏色變為紅色,所有其他元素變為藍色。

最后,索引會增加並調整,以防止索引超出元素的范圍。

 function toggle() { var y = document.querySelectorAll("h1"); for (var i = 0; i < y.length; i++) { y[i].style.backgroundColor = i === index? "red": "blue"; } index++; index %= y.length; } var index = 0;
 <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <button onclick="toggle()">push me</button>

我會做這樣的事情

document.querySelectorAll('h2').forEach(element => element.classList.toggle('highlight'))

1)通過某個屬性(例如'h2')查找所有元素
2) 遍歷所有找到的元素
3)如果尚未分配 class highlight
4) 完成

如果我想有一個切換效果,你可以把它放在 function 里面再調用一次。

const toggle = (target, className) => {
  document.querySelectorAll(target).forEach(element => element.classList.toggle(className))
}

toggle('h2', 'highlight');
toggle('h2', 'highlight');

highlight在哪里

.highlight {
  background: red;
}

暫無
暫無

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

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