如何隐藏其他标签页的内容,只显示所选标签页的内容 [英] How to hide other tabs's content and display only the selected tab's content
问题描述
我的HTML是
<ul class="side bar tabs">
<li id = "tabs1" onclick = "showStuff('tabs-1')">City</li>
<li id = "tabs2" onclick = "showStuff('tabs-2')">Country</li>
<li id = "tabs3" onclick = "showStuff('tabs-3')">Humanity</li>
</ul>
<div id="tabs-1" style = "display : none">
<p>Proin elit m</p>
</div>
<div id="tabs-2" style = "display : none">
<p>M massa ut d</p>
</div>
<div id="tabs-3" style = "display : none">
<p> sodales.</p>
</div>
JavaScript是
And JavaScript is
<script type="text/javascript">
function showStuff (id)
{
if (document.getElementById(id).style.display === "block")
{
document.getElementById(id).style.display = "none";
}
else
{
document.getElementById(id).style.display = "block";
}
}
</script>
当我点击某个选项卡时,其他选项卡的内容应该被隐藏,但不会隐藏。这是所有的代码。
When I click on a particular tab the other tabs's content should be hidden but it is not hiding. This is all the code I have.
推荐答案
给所有的标签内容元素一个通用的CSS类,例如 此演示 和以下代码。
Giving all the tab content elements a common CSS class makes selecting and styling them much easier, for example in this demo and code below.
CSS
.tabContent {
display:none;
}
JavaScript
function showStuff(element) {
var tabContents = document.getElementsByClassName('tabContent');
for (var i = 0; i < tabContents.length; i++) {
tabContents[i].style.display = 'none';
}
// change tabsX into tabs-X in order to find the correct tab content
var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
document.getElementById(tabContentIdToShow).style.display = 'block';
}
HTML
<ul class="side bar tabs">
<li id="tabs1" onclick="showStuff(this)">City</li>
<li id="tabs2" onclick="showStuff(this)">Country</li>
<li id="tabs3" onclick="showStuff(this)">Humanity</li>
</ul>
<div id="tabs-1" class="tabContent">
<p>Proin elit m</p>
</div>
<div id="tabs-2" class="tabContent">
<p>M massa ut d</p>
</div>
<div id="tabs-3" class="tabContent">
<p> sodales.</p>
</div>
我也更新了 showElement
更隐蔽,以便在隐藏和显示正确的标签内容时代码重复更少。
I have also updated the showElement
function to be more generic so that there is less code duplication when hiding and showing the correct tab content.
唯一的注意事项是 getElementsByClassName()
在IE8或更低版本中不可用。 其他(现代)浏览器具有此功能,但有其他选项 - 请参阅getElementsByClassName& IE8:对象不支持此属性或方法。
The only caveat is that getElementsByClassName()
is not available in IE8 or below. Other (modern) browsers have this function but there are alternatives - see getElementsByClassName & IE8: Object doesn't support this property or method.
这篇关于如何隐藏其他标签页的内容,只显示所选标签页的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!