代码之家  ›  专栏  ›  技术社区  ›  claudiadast

HTML/CSS可折叠按钮“阅读更多”不起作用

  •  0
  • claudiadast  · 技术社区  · 7 年前

    我正试图创建一个“阅读更多”按钮,以便我可以折叠一大块文本。到目前为止,我有以下几点。但是,当我点击“阅读更多”按钮时,它不会显示文本的其余部分。

    html格式 :

    {% extends "layout.html" %}
    
    {% block body %}
    
            <div class="jumbotron text-center">
                <br>
                <center><h1>About Us</h1></center>
                <section class="main items">
                <article class="item">
                    <header>
                        <a href="#"><img src="images/pic01.jpg" alt="" /></a>
                        <h3>John Doe</h3>
                    </header>
                    <center><img src="static/pic.jpg" style="width:400px;"></img></center>
                    <br><br><p>This is where the text I want to show goes.</p>                          
                    <button class="collapsible">Read More</button>
                    <div class="more_content">
                        <p>This is the text I want to appear after clicking the read more button.</p>
                    </div>  
                </article>
            </div>
    
        <!-- Scripts -->
    
        <script src="js/collapsible.js"></script>
    
    {% endblock %}
    

    :

    /* Style the button that is used to open and close the collapsible content */
    .collapsible {
      background-color: #ffbf00;
      color: #444;
      cursor: pointer;
      padding: 18px;
      width: 100%;
      border: none;
      text-align: left;
      outline: none;
      font-size: 15px;
    }
    
    
    /* Style the collapsible content. Note: hidden by default */
    .more_content {
      padding: 0 18px;
      display: none;
      overflow: hidden;
      background-color: #ffbf00;
    }
    

    下面是根据评论中的建议添加的JS。但是,当我点击“读我”按钮时,它仍然不起作用。

    JS(可折叠的.JS)

    var coll = document.getElementsByClassName("collapsible");
    var i;
    
    for (i = 0; i < coll.length; i++) {
      coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var more_content = this.nextElementSibling;
        if (more_content.style.display === "block") {
          more_content.style.display = "none";
        } else {
          more_content.style.display = "block";
        }
      });
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   C Gil    7 年前

    你只需要HTML和CSS就可以做到这一点 就像一个按钮。不过,这将使用和标记。我不确定你的听众,所以我不知道这对你是否重要-但这是另一种解决办法。

    <section>
        <article>
            Text/content you'd like to lead with
        </article>
        <details>
            <summary>Your 'Read More' button</summary>
            Content you'd like to appear after clicking
        </details>
    </section>
    

    您可以使用CSS设置 总结

    下面是一个工作示例: https://jsfiddle.net/Lhonf5xg/15/