我可能设置错了,但是我在JS中设置了一个按钮,通过它们共享的类来改变所有元素的颜色。它们没有onClick之类的,只是一个类。我试图使用if/else语句来循环不同的颜色主题。考虑到这是我第一次在我的项目中使用JS,这被证明是一个相当大的挑战。我在body元素的底部放置了script标签,并三次选中了我的按钮ID名称。如果它不能以我希望的方式工作,我希望早点知道,而不是晚点。border和back的其他变量也是我想要改变的颜色。
const themeColor = document.getElementById("theme-click-home");
const allColor = document.querySelectorAll(".theme-change");
const allBorder = document.querySelectorAll(".theme-border");
const allback = document.querySelectorAll(".theme-back");
themeColor.addEventListener("click", (e) => {
let count = 0;
count++;
if (count === 6) {
count = 0;
} else if (count === 1) {
allColor.style.setProperty("color", "red", "!important");
} else if (count === 2) {
allColor.style.setProperty("color", "red", "!important");
} else if (count === 3) {
allColor.style.setProperty("color", "red", "!important");
} else if (count === 4) {
allColor.style.setProperty("color", "red", "!important");
} else if (count === 5) {
allColor.style.setProperty("color", "red", "!important");
}
});
——编辑——
const themeColor = document.getElementById("theme-click-home");
const allColor = document.querySelectorAll(".theme-change");
const allBorder = document.querySelectorAll(".theme-border");
const allback = document.querySelectorAll(".theme-back");
themeColor.addEventListener("click", (e) => {
let count = 0;
count++;
if (count === 6) {
count = 0;
} else if (count === 1) {
for (i = 0; i < themeColor.length; i++) {
allColor[i].style.setProperty("color", "red", "!important");
}
} else if (count === 1) {
for (i = 0; i < themeColor.length; i++) {
allColor[i].style.setProperty("color", "blue", "!important");
}
} else if (count === 1) {
for (i = 0; i < themeColor.length; i++) {
allColor[i].style.setProperty("color", "green", "!important");
}
} else if (count === 1) {
for (i = 0; i < themeColor.length; i++) {
allColor[i].style.setProperty("color", "purple", "!important");
}
} else if (count === 1) {
for (i = 0; i < themeColor.length; i++) {
allColor[i].style.setProperty("color", "yellow", "!important");
}
}
});
querySelectorAll
将返回一个nodelist。您不能将侦听器附加到结果。你必须迭代nodelist。您应该使用CSS类,而不是直接设置元素的样式。您还为条件中的每个计数设置了相同的样式,这似乎是多余的。您可以遍历节点列表,并对每个元素应用相同的类。
你可以将颜色存储在数组中,然后使用forEach
回调的索引来访问它们并应用样式。
// Cache the button, and the theme-change elements
const themeColor = document.getElementById('theme-click-home');
const allColor = document.querySelectorAll('.theme-change');
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
// Add the listener to the button
themeColor.addEventListener('click', handleClick, false);
function handleClick() {
// For each element in `allColor` add the class found
// from the corresponding index of the colors array
allColor.forEach((el, i) => el.classList.add(colors[i]));
}
.red { color: red; }
.orange { color: orange; }
.yellow { color: yellow; }
.green { color: green; }
.blue { color: blue; }
.indigo { color: indigo; }
.violet { color: violet; }
<button id="theme-click-home">Change theme</button>
<div class="theme-change">Theme 1</div>
<div class="not-theme-change">Theme 2</div>
<div class="theme-change">Theme 3</div>
<div class="theme-change">Theme 4</div>
<div class="theme-change">Theme 5</div>
<div class="theme-change">Theme 6</div>
<div class="theme-change">Theme 7</div>
<div class="theme-change">Theme 8</div>
写了这些,我想我明白你的问题是什么。您需要循环遍历元素,并按顺序对每个元素应用新样式。
// Cache the button, and the theme-change elements
const themeColor = document.getElementById('theme-click-home');
const allColor = document.querySelectorAll('.theme-change');
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
// Call handleClick. It returns a new function
// that acts as the listener
themeColor.addEventListener('click', handleClick(), false);
// Set the count to zero
function handleClick(count = 0) {
// Return the function that acts as the listener
return function () {
// If count is less that the nodelist length
// add a style to the new element in the nodelist,
// and then increment the count
if (count < allColor.length) {
allColor[count].classList.add(colors[count]);
++count;
}
}
}
.red { color: red; }
.orange { color: orange; }
.yellow { color: yellow; }
.green { color: green; }
.blue { color: blue; }
.indigo { color: indigo; }
.violet { color: violet; }
<button id="theme-click-home">Change theme</button>
<div class="theme-change">Theme 1</div>
<div class="not-theme-change">Theme 2</div>
<div class="theme-change">Theme 3</div>
<div class="theme-change">Theme 4</div>
<div class="theme-change">Theme 5</div>
<div class="theme-change">Theme 6</div>
<div class="theme-change">Theme 7</div>
<div class="theme-change">Theme 8</div>
我不明白增加count变量的逻辑,但无论如何你应该把它移到函数闭包之外。
你可以这样做:
const themeColor = document.getElementById('theme-click-home')
const allColor = document.querySelectorAll('.theme-change')
const allBorder = document.querySelectorAll('.theme-border')
const allback = document.querySelectorAll('.theme-back')
let count = 0
themeColor.addEventListener('click', e => {
count++
const color = count % 2 === 0 ? 'red' : 'green'
allColor.forEach(elem => {
elem.style.color = color
})
})
你可以创建一个函数来改变元素的样式,并调用你想要改变的:您可以在这里找到您可以设置的所有属性https://www.w3schools.com/jsref/dom_obj_style.asp
const themeColor = document.getElementById("theme-click-home");
const allColor = document.querySelectorAll(".theme-change");
const allBorder = document.querySelectorAll(".theme-border");
const allback = document.querySelectorAll(".theme-back");
let count = 0;
themeColor.addEventListener("click", (e) => {
count++;
if (count >= 6) count = 0;
if (count === 1) changeStyle(allColor, 'color', "red"); // changes text color
else if (count === 2) changeStyle(allColor, 'color', "blue");
else if (count === 3) changeStyle(allBorder, 'border', "thick solid #0000FF"); // changes border
else if (count === 4) changeStyle(allColor, 'color', "green");
else if (count === 5) changeStyle(allback, 'backgroundColor', 'red'); // changes background
});
function changeStyle(elements, property, value) {
for (var i = 0; i < elements.length; i++) {
elements[i].style[property] = value;
}
}
.theme-change {
width: 100px;
margin: 5px;
}
<span id="theme-click-home">Click to Change</span>
<div class="theme-change theme-border">a</div>
<div class="theme-change theme-back">b</div>
<div class="theme-change theme-back">c</div>
<div class="theme-change theme-border">d</div>
没有必要使用setProperty
来改变内联样式属性。对于处理,您可能需要考虑事件委托。要存储点击次数,可以使用数据属性。
这里有一个(最小可复制的)示例,您可以记住上述内容。
document.addEventListener(`click`, handle);
function handle(evt) {
// only react when the event originated from button#bttn
if (evt.target.id === `bttn`) {
// [somestring].split is a bit of a trick to create
// an array from a (delimited, here by |) string.
// The array has 7 entries. Arrays are 'zero based',
// meaning that colors[0] is 'initial', colors[2] is 'blue',
// in other words: the third color from the array is colors[2]
const colors = `initial|red|blue|green|purple|rgb(211,211,21)|#c0c0c0`
.split(`|`);
// get the value of [data-clicked], convert to number (+) and add 1 to it
const clicks = +evt.target.dataset.clicked + 1;
// if n of clicks equals the array length, reset [data-clicked] to zero
// otherwise the value of [clicks].
// Note: using [colors.length] to determine when to reset,
// you can vary the number of colors used (added #c0c0c0, so [data-clicked]
// resets after the sixth click)
evt.target.dataset.clicked = clicks === colors.length ? 0 : clicks;
// set the color of div#allColor to colors[value of [data-clicked]]
document.querySelector(`#allColor`).style.color =
colors[evt.target.dataset.clicked];
}
}
body {
margin: 2rem;
font: normal 12px/15px verdana, arial;
}
#allColor {
margin-top: 1em;
}
[data-clicked]:after {
content: ' 'attr(data-clicked) ' click(s)';
}
<button id="bttn" data-clicked="0"></button>
<div id="allColor">
<h3>div#AllColor</h3>
<div>Chapter one</div>
<div>Chapter two</div>
<div>...</div>
</div>
或者你是认真的?
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.id === `bttn`) {
const themes = document.querySelectorAll(`[data-theme-color]`);
const clicks = +evt.target.dataset.clicked;
evt.target.dataset.clicked = clicks + 1;
themes[clicks].style.color = themes[clicks].dataset.themeColor;
if (clicks === themes.length-1) {
bttn.textContent += ` => all done`;
return evt.target.setAttribute(`disabled`, true);
}
}
if (evt.target.id === `redo`) {
const btn = document.querySelector(`#bttn`);
btn.dataset.clicked = 0;
btn.removeAttribute(`disabled`);
btn.textContent = ``;
document.querySelectorAll(`[data-theme-color]`)
.forEach(el => el.style.color = `initial`);
}
}
body {
margin: 2rem;
font: normal 12px/15px verdana, arial;
}
#allColor {
margin-top: 1em;
}
[data-clicked]:before {
content: ' 'attr(data-clicked) ' click(s)';
}
<button id="bttn" data-clicked="0"></button>
<button id="redo">Again</button>
<div id="allColor">
<h3>div#AllColor</h3>
<div data-theme-color="orange">Chapter one</div>
<div data-theme-color="red">Chapter two</div>
<div data-theme-color="blue">Chapter three</div>
<div data-theme-color="green">Chapter four</div>
<div data-theme-color="purple">Chapter five</div>
<div data-theme-color="rgb(211,211,21)">Chapter six</div>
<div data-theme-color="#c0c0c0">Chapter seven</div>
</div>
解决了。下面是代码,如果有人感兴趣。testFunction()
附着在onclick
上
let allColor = document.querySelectorAll(".theme-change");
const allBorder = document.querySelectorAll(".theme-border");
const allBack = document.querySelectorAll(".theme-back");
const noShadow = document.querySelectorAll("*");
let count = -1;
colorArray = [
"white",
"blue",
"red",
"green",
"purple",
"maroon",
"yellow",
"pink",
"teal",
"crimson",
];
function testFunction() {
if (count >= colorArray.length - 1) {
count = -1;
}
count++;
allColor.forEach((item) => {
item.style.color = colorArray[count];
});
allBorder.forEach((item) => {
item.style.border = `solid ${colorArray[count]}`;
});
allBack.forEach((item) => {
item.style.backgroundColor = colorArray[count];
});
noShadow.forEach((item) => {
item.style.textShadow = "none";
item.style.boxShadow = "none";
});
}