我有两个要素。如果1已经打开,那么当我打开2时,应该关闭1。我对javascript还是陌生的,所以如果有人wuold帮助,请谢谢。现在,当我尝试单击时,什么也没有发生,如果我删除了while循环,那么它将起作用。也许我不确定那里有什么错误,但是根据逻辑来看,它看起来是正确的。
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
.newClassName {
width: 400px;
height: 100px;
background-color: lightblue;
text-align: center;
font-size: 25px;
color: navy;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to toggle between two classes.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Try it 2</button>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<div id="myDIV2" class="mystyle">
I am a DIV element2
</div>
<script>
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
function myFunction() {
x.classList.toggle("newClassName");
}
function myFunction2() {
y.classList.toggle("newClassName");
}
while (x.classList.contains("newClassName")) {
if (y.classList.contains("newClassName") = true) {
x.classList.toggle("newClassName");
}
}
</script>
</body>
您可以将所有功能简化为仅一个功能,因为从MDN:
toggle(String [,force])仅存在一个参数时:切换类值;否则,设置为0。即,如果类存在,则将其删除并返回false;如果不存在,则将其添加并返回true。当存在第二个参数时:如果第二个参数为true,则添加指定的类值,如果为false,则将其删除。
所以代码是:
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
function myFunction() {
var result = x.classList.toggle("newClassName");
y.classList.toggle("newClassName", !result);
}
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
.newClassName {
width: 400px;
height: 100px;
background-color: lightblue;
text-align: center;
font-size: 25px;
color: navy;
margin-bottom: 10px;
}
<p>Click the button to toggle between two classes.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction()">Try it 2</button>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<div id="myDIV2" class="mystyle">
I am a DIV element2
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句