【发布时间】:2021-09-24 15:43:21
【问题描述】:
如果另一个元素的classList 等于“某事”,我想删除/添加某个元素的classList。但是有一个小问题,它只运行一次命令,我的意思是条件不会每秒检查第一个元素的classList,所以它运行它没有任何问题。如果 if 为真,则它运行 if 条件,然后它不会检查 else if 并因此反向。
这是我的代码:
const dToggle = () => {
const firstElm = document.querySelector('.firstElm');
firstElm.classList.toggle('red-border');
};
document.querySelector('button').addEventListener('click', dToggle);
const orangeOrRed = () => {
const firstElm = document.querySelector('.firstElm');
const secondElm = document.querySelector('.secondElm');
firstElm.classList === 'red-border' ? secondElm.classList.add('red') : secondElm.classList.add('orange');
// if (firstElm.classList === 'red-border') {
// secondElm.classList.remove('orange');
// secondElm.classList.add('red');
// } else if (firstElm.classList === 'orange-border' {
// secondElm.classList.remove('red');
// secondElm.classList.add('orange');
// };
};
// Maybe the exact problem is right here.
window.addEventListener('load', orangeOrRed);
console.log(document.querySelector('.secondElm').classList.value);
.d-none {
display: none !important;
}
.firstElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: blue;
}
.orange-border {
border: orange 3px solid;
}
.red-border {
border: red 3px solid;
}
.secondElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: green;
}
.orange {
background-color: orange !important;
}
.red {
background-color: red !important;
}
<button type="button" style="cursor: pointer;">Click here.</button>
<p>It should run the conditional statement whenever I click on the button to apply the border.</p>
<p> First Elm Border Color (MUST BE) Second Elm Background Color</p>
<div class='firstElm orange-border'></div>
<div class='secondElm'></div>
<p style="padding-bottom: 10px;">Remember that I only want to do this with(conditioal statements), It's possible either with classList.toggle() but I don't want to.</p>
【问题讨论】:
-
还是有点难以理解。
there is a little problem that it only runs the command once, I mean the condition doesn't check the classList of the first element every second so it runs it without any problem.也许你可以改写一下。还有你的 if else 代码相关还是条件运算符与代码更相关? -
值得指出的是,您的按钮事件侦听器都没有 if 条件,并且始终运行相同。并且您的窗口加载侦听器将始终运行一次。我希望这是你想要的。
-
如果您希望代码在类更改时运行,请在您更改类的代码中调用该函数。或者使用
MutationObserver,知道它可能会降低您的网站速度。同样classList是DOMTokenList,而不是字符串,所以firstElm.classList永远不会等于'red-border'。你应该使用classList.contains('red-border') -
If you want your code to run when the class changes, call the function in your code where you change the class.是什么意思? @HereticMonkey -
我的意思是,如果您的代码更改了这些元素的
classList,请在该函数中调用orangeOrRed()。
标签: javascript html css if-statement conditional-statements