gpt4 book ai didi

javascript - 如何使用 Javascript 切换多个 HTML 元素的背景颜色?

转载 作者:行者123 更新时间:2023-12-03 03:04:29 25 4
gpt4 key购买 nike

或多或少的标题,每个元素都有不同的类名。

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"
}

}

最佳答案

您的选择器语法不正确:

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>

关于javascript - 如何使用 Javascript 切换多个 HTML 元素的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47231539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com