切换共享相同 class 名称的多个元素的可见性

Toggle visibility of multiple elements sharing the same class name

我有一个滑块,当它以一种方式滑动时我想要它,它会隐藏页面上具有类名="siteContainer" 的所有元素。当我再次单击它时,我希望它显示所有带有 classname="siteContainer"

的元素

因为有很多元素我需要一个循环(我有)。我已经设法使所有元素可见,但无法再次使可见。

这些元素不连续,因此无法将其分组为具有一个 ID 的 div。

在codepen里https://codepen.io/payling/pen/MRmvwY

及以下

<script>
    function setDisplay(className, displayValue) {
        var items = document.getElementsByClassName(className);
        for (var i=0; i < items.length; i++) {
        items[i].style.display = displayValue;
        }
    }
    function showsiteContainer() {
        setDisplay("siteContainer", "none");
    }
</script>  
function showsiteContainer() {
    var x = document.getElementById("block");
    if (x.style.display === "none") {
      x.style.display = "block";
    } else {
      x.style.display = "none";
    }
  } 

<style>
.siteContainer {
    display:flex;
    width:40px;
    hieght:40px;
    color:black;
    text-decoration:none;
    font-size:13px;
    padding:5px;
    border-top-color: rgb(133, 130, 130);
    border-top-style:dotted;
    border-width: 1px;
}
  /* SLIDE BUTTON*/
  .switch {
    position: relative;
    display: inline-block;
    width: 40px;
    height: 20px;
  }

  .switch input { 
    opacity: 0;
    width: 0;
    height: 0;
  }

  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #EDEDED;
    -webkit-transition: .4s;
    transition: .4s;
  }

  .slider:before {
    position: absolute;
    content: "";
    height: 12px;
    width: 12px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
  }

  input:checked + .slider {
    background-color: #1C77C3;
  }

  input:focus + .slider {
    box-shadow: 0 0 1px #2196F3;
  }

  input:checked + .slider:before {
    -webkit-transform: translateX(18px);
    -ms-transform: translateX(18px);
    transform: translateX(18px);
  }

  /* Rounded sliders */
  .slider.round {
    border-radius: 24px;
  }

  .slider.round:before {
    border-radius: 50%;
  }




</style>
<body>
        <div>
                <span>DETAILS</span>
                <label class="switch">
                    <input type="checkbox" onclick="showsiteContainer()" >
                    <span class="slider round"></span>
                </label>  
            </div>

<div>
    <div class="siteContainer">an element</div>  
    <div class="siteContainer">2nd element</div> 
</div> 
    <div class="siteContainer">3rd element</div>  
    <div class="siteContainer">4th element</div>
</div>  

</body>

看看你的例子稍作修改,我重写了你的函数:

function showsiteContainer() {
  var elements = document.getElementsByClassName("siteContainer");
  Array.prototype.forEach.call(elements, function(el) {
    if (el.style.display === "none") {
      el.style.display = "block";
    } else {
      el.style.display = "none";
    }
  });
}

https://codepen.io/Xolkys/pen/rbmzXz