【问题标题】:Show different div according to which link i click根据我点击的链接显示不同的 div
【发布时间】:2020-03-29 07:37:18
【问题描述】:

在我的 html 页面上,我在顶部创建了四个不同的链接。在此之下,我有四个 div 元素。在页面加载时,我希望将它们全部隐藏。

现在我的问题。当我单击链接时,我希望 div 以过渡轻松向下滑动效果可见。因此,如果我单击“显示蓝色”,则 id="blue" 的 div 会向下滑动并可见。如果我然后单击另一个链接,例如“显示绿色”可见的 div 向上滑动,而被选中的现在正在向下滑动并变得可见等等。

我尝试了一些 js onClick,但我无法正常工作 希望你们中的一些人可以帮助我。

* {
  margin: 0;
}

.content_holder {
  width: 100%;
  background-color: #bfdc37;
  height: 100px;
}

a {
  margin: 20px;
}

.color {
  width: 100%;
  background-color: #bfdc37;
  height: 100px;
  display: none;

}
    <div class="content_holder">
        <div class="box" id="box1">
            <a href="#">Show Blue</a>
        </div>

        <div class="box" id="box2">
            <a href="#">Show Red</a>
        </div>

        <div class="box" id="box3">
            <a href="#">Show Yellow</a>
        </div>

        <div class="box" id="box4">
            <a href="#">Show Green</a>
        </div>
    </div>

    <div class="color" id="blue">
        This box says blue
    </div>

    <div class="color" id="red">
        This box says red
    </div>

    <div class="color" id="yellow">
        This box says yellow
    </div>

    <div class="color" id="green">
        This box says green
    </div>

【问题讨论】:

  • 因为你的问题被标记为 javascript 它在哪里?
  • 我没有包含它,因为它只能使用一个链接和一个 div

标签: javascript css


【解决方案1】:

使用 jQuery 很容易做到。您可以编写动画打开和关闭的代码。

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script>
        $(document).ready(function(){
            $(".box").click(function(){
                $(".color").css("display", "none");
                var data = $(this).attr("data");
                $('.color[id='+data+']').css("display", "inline");
            });
        });
    </script>

我刚刚在 div 中添加了data 属性。

        <div class="box" id="box1" data="blue">
            <a href="#">Show Blue</a>
        </div>

        <div class="box" id="box2" data="red">
            <a href="#">Show Red</a>
        </div>

        <div class="box" id="box3" data="yellow">
            <a href="#">Show Yellow</a>
        </div>

        <div class="box" id="box4" data="green">
            <a href="#">Show Green</a>
        </div>
    </div>

    <div class="color" id="blue">
        This box says blue
    </div>

    <div class="color" id="red">
        This box says red
    </div>

    <div class="color" id="yellow">
        This box says yellow
    </div>

    <div class="color" id="green">
        This box says green
    </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2021-09-17
    相关资源
    最近更新 更多