Javascript显示/隐藏div onclick

Moa*_*bed 1 html javascript css frontend web

我有一个页面,其中包含三个 div,每个 div 是一个段落。我想使用 javascript 在用户从导航栏按下每个 div 时仅在页面中显示 这是导航栏

WebDev 只是一个页面,由三个不同的 div 组成,如下所示

<!--HTML-->
<div class="html" id="html-show">
    <p class="text-html" id="htmlContent">..
    </p>
</div>

<!--CSS-->
<div class="css" id="css-show">
    <p class="text-css" id="cssContent">..
    </p>
</div>

<!--JS-->
<div class="js" id="js-show">
    <p class="text-js" id="jsContent">..
    </p>
</div>
Run Code Online (Sandbox Code Playgroud)

因此,如果用户在导航栏中按下 HTML,他将被重定向到此页面,并且只有 HTML div 可见,CSS 和 js 也是如此。事实上,页面的其他部分也会显示(导航栏、页脚等......)

tac*_*shy 5

你甚至不需要 JS。您可以仅使用 HTML 和 CSS 并使用锚点来完成此操作,:target如下面的代码片段所示。

#html-show, #css-show, #js-show {
  display: none;
}

#html-show:target, #css-show:target, #js-show:target {
  display: block;
}
Run Code Online (Sandbox Code Playgroud)
<!--Nav-Bar-->
<a href="#html-show">Show HTML</a>
<a href="#css-show">Show CSS</a>
<a href="#js-show">Show JS</a>

<!--HTML-->
<div class="html" id="html-show">
    <p class="text-html" id="htmlContent">HTML Content..
    </p>
</div>

<!--CSS-->
<div class="css" id="css-show">
    <p class="text-css" id="cssContent">CSS Content..
    </p>
</div>

<!--JS-->
<div class="js" id="js-show">
    <p class="text-js" id="jsContent">JS Content..
    </p>
</div>
Run Code Online (Sandbox Code Playgroud)