点击即显示'Div 1'&隐藏'Div 2'&单击同一按钮显示'Di

On click show 'Div 1' & hide 'Div 2' & On click of same button show 'Div 2' and hide 'Div 1'?

本文关键字:Div 显示 amp Di 按钮 单击 隐藏      更新时间:2023-09-26

我可以使用不同的按钮来实现此功能。但我无法通过点击相同的按钮来实现这一点。

任何帮助/建议

感谢

  • 使用ternary-operator切换当前元素
  • 使用Element.style.display设置display css财产

var btn = document.getElementById('btn');
var curr = 'div2';
btn.onclick = function() {
  document.getElementById(curr).style.display = 'none';
  curr = curr === 'div2' ? 'div1' : 'div2';
  document.getElementById(curr).style.display = 'block';
};
div {
  display: none;
}
<div id="div1">#div1</div>
<div id="div2">#div2</div>
<button id='btn'>Change</button>

有这样的吗?

function divchange(){
  div1 = document.getElementById("div1");
  div2 = document.getElementById("div2");
  if(div1.style.display == "none"){
    div1.style.display = "block";
    div2.style.display = "none";
  }else{
    div1.style.display = "none";
    div2.style.display = "block";
  }
}
<button id="divchangebutton" onclick="divchange();">test</button>
<div id="div1">asdf</div>
<div id="div2" style="display:none;">qwert</div>

问题-如果在css中设置了"display:none",则无法获取值。"elem.style.display"返回空字符串。我们可以使用Computed Style来解决它。

        var btn = document.getElementById("btn-toggle");
        btn.addEventListener("click", function(){
            var one = document.querySelector(".one");
            var tow = document.querySelector(".tow");
            
            one.style.display = (getRealDisplay(one) == 'none') ? 'block' : 'none';
            tow.style.display = (getRealDisplay(tow) == 'none') ? 'block' : 'none';
        });
        
        // get real value of 'display' property
        function getRealDisplay(elem) {
            if (elem.currentStyle) {
                return elem.currentStyle.display;
            } else if (window.getComputedStyle) {
                var computedStyle = window.getComputedStyle(elem, null);
                return computedStyle.getPropertyValue('display');
            } 
        }
      .one, .tow{
          width:200px;
          min-height: 200px;
          background-color:burlywood;
      }
      .tow{
          display: none;
          background-color:cadetblue;
      }
    <div class="one">1</div>
   <div class="tow">2</div>
    <button id="btn-toggle">show hide</button>