首页 > 解决方案 > Hiding a div automatically when other related divs are also hidden

问题描述

My page consists of several elements, buttons and scrollers. Each button is to hide/unhide a group of elements, and each scroller is to scroll to the first element of the group. I use onclick events to hide, unhide and scroll, and they all work fine. What I'm trying and failing to do is hiding the scroller automatically when all related elements are hidden.

EXAMPLE: When I click scroller, page goes to Element 1a. When I click 1st button it hides/unhides Element 1a, 1b and 1c, and click 2nd button it does the same for Element 1d, 1e, 1f. I need my scroller to be hidden automatically when there's no visible element left in the page which are connected with this scroller. How can I fix my js code to achieve this?

HTML:

<div class="element">Element 1a</div>
<div class="element">Element 1b</div>
<div class="element">Element 1c</div>
<div class="element">Element 1d</div>
<div class="element">Element 1e</div>
<div class="element">Element 1f</div>
...

<div class="button" onclick="hide1()">Hide/Unhide 1a,1b,1c</div>
<div class="button" onclick="hide2()">Hide/Unhide 1d,1e,1f</div>
<div class="scroller" onclick="scroll1()">Scroll to Element 1</div>

<script>window.onload = hidescroller()</script>

JS:

function hidescroller() {
   var scroller = document.getElementsByClassName("scroller")[0];
   var element = document.getElementsByClassName("element");
   var i;
   for (i=0; i<element.length; i++) {
      if (element[i].style.display = "none") {
         scroller.style.display = "none";
      }
      else {
         scroller.style.display = "block";
      }
   }
}

I'm happy with my hide1(), hide2() and scroll1() functions, so in order to avoid confusion I didn't write them. If you need to see them too, just let me know.

标签: javascripthtmlcss

解决方案


推荐阅读