我正在测试一些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>
答案 0 :(得分:2)
最有效的解决方案就是Eff
一个类。另外,如果您手动引用数组中的对象,则不需要循环
toggle
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;}
答案 1 :(得分:2)
请参见下面的内联评论:
// 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>
答案 2 :(得分:1)
您可以存储红色的索引,并用蓝色替换其他颜色。
此方法使用全局变量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>
答案 3 :(得分:1)
我会做这样的事情
document.querySelectorAll('h2').forEach(element => element.classList.toggle('highlight'))
1)通过某个属性(例如“ h2”)查找所有元素
2)遍历所有找到的元素
3)如果尚未分配类highlight
,请分配它
4)完成
如果我想要切换效果,可以将其放在函数中,然后再次调用。
const toggle = (target, className) => {
document.querySelectorAll(target).forEach(element => element.classList.toggle(className))
}
toggle('h2', 'highlight');
toggle('h2', 'highlight');
其中highlight
是
.highlight {
background: red;
}