首页 > 解决方案 > 切换分隔线的更有效方式?

问题描述

我有一个基本网页并创建了一个导航栏。导航栏上的每个标题都会将一个分隔符切换为可见,其余的不可见。必须有一种更短、更简单、更有效的编码方式吗?

<script type='text/javascript'>
    function Nav1(){
        document.getElementById("Nav1").classList.add("Active");
        document.getElementById("Nav2").classList.remove("Active");
        document.getElementById("Nav3").classList.remove("Active");      
        document.getElementById("Nav4").classList.remove("Active");

        document.getElementById("Div1").classList.remove("d-none");
        document.getElementById("Div2").classList.add("d-none");
        document.getElementById("Div3").classList.add("d-none");
        document.getElementById("Div4").classList.add("d-none");
    }
    ...

d-none用来隐藏分隔线,Active只是一个改变边框颜色的类。

我对javascript非常陌生,因此非常感谢您提供完整的解释。(我在网页上使用 Python 和 Flask。)

标签: javascripthtmlcss

解决方案


Your HTML structure:

  • Give to all your "toggleable" dividers a class .divider.
  • Give each .divider a unique id.
  • Attach a click handler to each button that toggles a particular divider. The click handler also passes a parameter id which is the unique id of the divider you want to toggle with that button.

Now for CSS:

  • Elements with class divider should be hidden unless they also have a class visible.

And your JS:

  • The showDivider function that your click handlers fire selects all elements with class divider then iterates (loops) over them.
  • If the iterated divider matches the passed id, it adds the class visible to it, otherwise it removes it (if it already has it).

Here's a complete example:

function showDivider(id) {
  // Select all elements with class 'divider'.
  document.querySelectorAll('.divider')
    .forEach(divider => {
     // for each element:
     
      // if this divider has the passed id.
      if (divider.getAttribute('id') === id) {
        // add the class 'visible' to it.
        divider.classList.add('visible')
      } else {
        // if not, remove class 'visible' from it.
        divider.classList.remove('visible')
      }
    })
}
/* Elements with class "divider" should be hidden. */
.divider {
  display: none;
}

/* Elements with both class "divider" & "visible" should be visible. */
.divider.visible {
  display: block;
}
<button onclick="showDivider('a');" >Show Divider A</button>
<button onclick="showDivider('b');" >Show Divider B</button>
<button onclick="showDivider('c');" >Show Divider C</button>

<hr>

<div id="a" class="divider">
  Hello Content A!
</div>
<div id="b" class="divider"> 
  Hello Content B!
</div>
<div id="c" class="divider"> 
  Hello Content C!
</div>

If you want any element with class divider to be visible on page load, just explicitly add the visible class to it like so:

<div id="a" class="divider visible">
  Hello Content A!
</div>
<div id="b" class="divider"> 
  Hello Content B!
</div>
<div id="c" class="divider"> 
  Hello Content C!
</div>

推荐阅读