如何使用Javascript切换多个HTML元素的背景颜色? (FIXED)
问题描述:
或多或少的标题,每个元素都有不同的类名。如何使用Javascript切换多个HTML元素的背景颜色? (FIXED)
HTML元素:
<section class = "top-nav">
<h3 class = "top-left-heading">Hot</h3>
<h3 class = "top-right-heading">Items</h3>
<h3 class = "bottom-left-heading">Interaction</h3>
<h3 class = "bottom-right-heading">Location</h3>
<section class = "footer">
JavaScript函数:
var theme
function toggleTheme(){
var bars = document.querySelectorAll('.heading' + '.nav' + '.header' +
'footer')
if (theme == "blue"){
for (var i = 0; i < bars.length; i++){
bars[i].style.backgroundColor = "#11C034";
}
theme = "green"
}
else{
for (var i = 0; i < bars.length; i++){
bars[i].style.backgroundColor = "#428bca";
}
theme = "blue"
}
}
答
也许更好的方法是只在类.theme-black
添加到body元素。然后,只需为给定基类的元素编写CSS,如下所示:
.top-nav {
// basic CSS colors...
}
.theme-black .top-nav {
background: #000;
}
这样可以最大限度地减少JavaScript并让CSS完成样式。
答
你选择语法不正确:
var bars = document.querySelectorAll('.heading' + '.nav' + '.header' + 'footer')
- 首先,这应该是一个大的字符串用逗号分隔传递给方法,而不是一个 串联串的不同选择(除非你想将可变数据合并到一起,这是你没有做的)。
- 其次,您引用的类实际上不是您在HTML中使用的类 。
正确的语法是:
document.querySelectorAll(".top-left-heading, .top-right-heading, .bottom-left-heading, .bottom-right-heading")
下,没有必要在所有的if/then
或内联样式。只需为您需要的主题设置类,在相关的HTML元素上设置默认类(主题),然后通过某些触发器切换这些类的使用。
document.querySelector("button").addEventListener("click", toggleTheme);
function toggleTheme(){
// Get all the headings into a node list and then convert that node list to an array
var bars = Array.from(document.querySelectorAll(".top-left-heading, .top-right-heading, .bottom-left-heading, .bottom-right-heading"));
// Loop through the array
bars.forEach(function(bar){
// Toggle the use of the classes
bar.classList.toggle("green");
bar.classList.toggle("blue");
});
}
.green {
background-color :green;
color:yellow;
}
.blue {
background-color :blue;
color:pink;
}
<section class = "top-nav">
<h3 class = "top-left-heading green">Hot</h3>
<h3 class = "top-right-heading green">Items</h3>
<h3 class = "bottom-left-heading green">Interaction</h3>
<h3 class = "bottom-right-heading green">Location</h3>
<section class = "footer">
<button type="button">Toggle Theme</button>
可以影响不止一个类名的对象。 – JMichelB
将'.heading'+'.nav'+'.header'+'footer'更改为'.heading,.nav,.header,.footer' – jeff
需要var bars = document.querySelectorAll('。top-nav h3,.header,.footer');' –