在div之间切换:如何一次只显示一个div?

时间:2019-07-22 15:26:57

标签: javascript html

我有两个内容不同的div。单击按钮时,我设法添加了show-hide div函数。问题是,当一个div可见并且我单击第二个按钮时,它们都可见。我想一次只显示一个div-当显示一个div并单击另一个按钮时,上一个div应该自动隐藏。

我不想使用jQuery,希望只有纯JavaScript才有可能。

function horTxtFunction() {
	var x = document.getElementById("horTxt");
	if (x.style.display === "none") {
		x.style.display = "block";
	} else {
		x.style.display = "none";
	}
}

function verTxtFunction() {
	var x = document.getElementById("verTxt");
	if (x.style.display === "none") {
		x.style.display = "block";
	} else {
		x.style.display = "none";
	}
}
<button onclick="horTxtFunction()">Horisontaalne tekstiga</button>
<button onclick="verTxtFunction()">Vertikaalne tekstiga</button>

<div id="horTxt" style="display:none;">
<p>Some content here</p>
</div>

<div id="verTxt" style="display:none;">
<p>Some different content here</p>
</div>

2 个答案:

答案 0 :(得分:0)

您需要确保隐藏另一个div,而不仅仅是显示另一个。

function horTxtFunction() {
var x = document.getElementById("horTxt");
var otherDiv = document.getElementById("verTxt");
if (x.style.display === "none") {
    x.style.display = "block";
    overDiv.style.display = "none";
} else {
    x.style.display = "none";
    overDiv.style.display = "block";
}

}

答案 1 :(得分:0)

考虑将两个<div>标签包装在控制器<div>标签中,然后使用“状态”控制显示哪个子<div>

在下面的示例中,我使用属性dir来保存状态,并使用CSS来播放状态和子类<div>

var holder = document.querySelector("[dir]");

function horTxtFunction() {
  holder.setAttribute('dir', 'hor');
}

function verTxtFunction() {
  holder.setAttribute('dir', 'ver');
}
[dir="ver"] > :not(.verTxt),
[dir="hor"] > :not(.horTxt) {
  display: none;
}
<button onclick="horTxtFunction()">Horisontaalne tekstiga</button>
<button onclick="verTxtFunction()">Vertikaalne tekstiga</button>

<div dir="hor">
  <div class="horTxt">
    <p>Some content here</p>
  </div>

  <div class="verTxt">
    <p>Some different content here</p>
  </div>
</div>

以这种方式进行操作的主要好处是,如果需要添加其他子项:

var holder = document.querySelector("[dir]");

function toggle(val) {
  holder.setAttribute('dir', val);
}
[dir="ver"] > :not(.verTxt),
[dir="hor"] > :not(.horTxt),
[dir="left"] > :not(.leftTxt),
[dir="right"] > :not(.rightTxt) {
  display: none;
}
<button onclick="toggle('hor')">Horizontal</button>
<button onclick="toggle('ver')">Vertical</button>
<button onclick="toggle('left')">Left</button>
<button onclick="toggle('right')">Right</button>

<div dir="hor">
  <div class="horTxt">
    <p>Some content here</p>
  </div>
  <div class="verTxt">
    <p>Some different content here</p>
  </div>
  <div class="leftTxt">
    <p>This is the left text area</p>
  </div>
  <div class="rightTxt">
    <p>This is the right text area</p>
  </div>
</div>

在这里,我更改为单个事件处理程序,并传递我要显示的部分。然后,我不得不扩展CSS来处理新的<div>标签。但是现在要成长为更多的孩子,只是添加按钮,div和CSS。

相关问题