显示div使用javascript隐藏另一个div

时间:2016-05-10 15:55:04

标签: javascript html

我的HTML代码如下所示:

<div id="register" class="dropdown">
  <button id="regbutton" href="#" onclick="toggle_visibility('container1');">show1</button>
  <div id="container1" style="display:'none';">
  </div>
</div>
<div id="login" class="dropdown">
  <button id="loginbutton" href="#" onclick="toggle_visibility('container2')"><b>Masuk</b></button>
  <div id="container2" style="display:'none';"></div>
</div>

这是我的js代码:

function toggle_visibility(id) {
   var x = document.getElementById(id); {
   if(x.style.display == 'block') {
      x.style.display = 'none';
   } else {
      x.style.display = 'block';
  }
}

问题是,我怎样才能使这些div成为“当一个div可见,另一个div隐藏”时? 抱歉我的英语不好:#:3

2 个答案:

答案 0 :(得分:0)

首先在这里为每个div添加一个类,我把它作为容器 然后隐藏所有这些,并显示1个特定的div

<div id="register" class="dropdown">
    <button id="regbutton" href="#" onclick="toggle_visibility('container1');">show1</button>
    <div id="container1" class='container' style="display:none;">test
    </div>
</div>
<div id="login" class="dropdown">
    <button id="loginbutton" href="#" onclick="toggle_visibility('container2')"><b>Masuk</b></button>
    <div id="container2" class='container' style="display:none;">test
    </div>
</div>


<script>
    function toggle_visibility(id) {
        var x = document.getElementById(id);
        var divsToHide = document.getElementsByClassName('container'); //divsToHide is an array so we loop through them
        for(var i = 0; i < divsToHide.length; i++){
            divsToHide[i].style.display = "none"; 
        }
        x.style.display = 'block';
    }
</script>

答案 1 :(得分:0)

如果你只需要这两个div,你可以简单地使用他们的div id和一个简单的条件:

function toggle(divNumber) {
  var div1 = document.getElementById('div1');
  var div2 = document.getElementById('div2');
  if (divNumber == 1) {
    div1.style.display = 'none';
    div2.style.display = 'block';
  } else {
    div2.style.display = 'none';
    div1.style.display = 'block';
  }
}

小提琴: https://jsfiddle.net/8480twew/