使用JavaScript在两个独特的DIVS之间使用显示进行交换

时间:2014-12-27 18:53:05

标签: javascript jquery html css

我正在尝试使用JavaScript在两个按钮上使用onclick交换两个div的可见性。它有效,但如果我点击按钮两次,我会使用的代码 - 它会再次交换!

function toggleOne(id,wid) {
       var e = document.getElementById(id);
        var f = document.getElementById(wid);
       if(e.style.display == 'block'){
          e.style.display = 'none';
		  f.style.display = 'block';
	   }
       else {
          e.style.display = 'block';
            f.style.display = 'none';
	   }
    }
.first {
	position: absolute;
	border: 3px solid;
	border-color: red;
	height: 300px;
	width: 200px;
	overflow: hidden;
	background-color: #FFFFFF;
	left: 28px;
	top: 40px;
    display: block;
}
.second {
	position: absolute;
	border: 3px solid;
	border-color: red;
    color: #FFFFFF;
	height: 300px;
	width: 200px;
	overflow: hidden;
	background-color: #000000;
	left: 400px;
	top: 40px;
    display: none;
}
<a href="#" onclick="toggleOne('first','second');">[button 1]</a> <a href="#" onclick="toggleOne('second','first');">[button 2]</a>
<div id="first" class="first"></div>
<div id="second" class="second"></div>

1 个答案:

答案 0 :(得分:3)

您的功能被写入切换其输入。无论按下哪个按钮,它都会查看第一个元素的当前状态,交换它。

如果您想让一个按钮始终打开一个特定的div,请重写您的函数以始终激活其第一个参数,并始终停用其第二个参数,而不管每个元素的状态如何:

&#13;
&#13;
function toggleOne(onId, offId) {
    var turnOn = document.getElementById(onId);
    var turnOff = document.getElementById(offId);
    turnOn.style.display = 'block';
    turnOff.style.display = 'none';
}
&#13;
.first {
    position: absolute;
    border: 3px solid;
    border-color: red;
    height: 300px;
    width: 200px;
    overflow: hidden;
    background-color: #FFFFFF;
    left: 28px;
    top: 40px;
    display: block;
}
.second {
    position: absolute;
    border: 3px solid;
    border-color: red;
    color: #FFFFFF;
    height: 300px;
    width: 200px;
    overflow: hidden;
    background-color: #000000;
    left: 400px;
    top: 40px;
    display: none;
}
&#13;
<a href="#" onclick="toggleOne('first','second');">[button 1]</a>
<a href="#" onclick="toggleOne('second','first');">[button 2]</a>
<div id="first" class="first"></div>
<div id="second" class="second"></div>
&#13;
&#13;
&#13;