我有以下代码从div“mainFrameOne”到div“mainFrameTwo”。但是,在更改为mainFrameTwo后,它无法返回到mainFrameOne。我希望它能够不断来回切换。我最好如何做到这一点?
HTML:
<div id="mainFrameOne">
<p>mainFrameOne</p>
</div>
<div id="mainFrameTwo" style="display:none;">
<p>mainFrameTwo</p>
</div>
<button onclick="myFunction()">Click me</button>
JS:
function myFunction() {
document.getElementById("mainFrameOne").style.display="none";
document.getElementById("mainFrameTwo").style.display="block";
}
答案 0 :(得分:7)
添加条件以检查div是否可见,然后将其隐藏并显示另一个,否则执行相反操作:
function myFunction() {
var mainFrameOne = document.getElementById("mainFrameOne");
var mainFrameTwo = document.getElementById("mainFrameTwo");
mainFrameOne.style.display = (
mainFrameOne.style.display == "none" ? "block" : "none");
mainFrameTwo.style.display = (
mainFrameTwo.style.display == "none" ? "block" : "none");
}
希望这有帮助。
function myFunction() {
var mainFrameOne = document.getElementById("mainFrameOne");
var mainFrameTwo = document.getElementById("mainFrameTwo");
mainFrameOne.style.display = (
mainFrameOne.style.display == "none" ? "block" : "none");
mainFrameTwo.style.display = (
mainFrameTwo.style.display == "none" ? "block" : "none");
}
<div id="mainFrameOne">
<p>mainFrameOne</p>
</div>
<div id="mainFrameTwo" style="display:none;">
<p>mainFrameTwo</p>
</div>
<button onclick="myFunction()">Click me</button>