"Read More"的 HTML/CSS 可折叠按钮不起作用

标签 html css

我正在尝试创建一个“阅​​读更多”按钮,以便折叠一大段文本。到目前为止,我所拥有的是以下内容。但是,当我单击“阅读更多”按钮时,它不会显示其余文本。

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 %}

CSS:

/* 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 (collapsible.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";
    }
  });
}

最佳答案

您可以仅使用 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 将 summary 标签设置为看起来像一个按钮。

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

关于 "Read More"的 HTML/CSS 可折叠按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51995216/

相关文章:

html - 动态调整单元格宽度后抑制按钮组中的按钮换行

CSS 布局 - 三列,中间列包含两个框

javascript - 无法将 flex 子项的高度设置为 100%

html - 为什么位置:relative; appear to change the z-index?

html - 相邻的兄弟选择器不起作用

html - 如何在 bootstrap 字形周围添加一个圆圈

java - 向 caroufredsel 幻灯片添加文本

html - CSS Layout : One side scrolls, 另一边设置高度

php - 有人可以帮助找出这个 PHP 文件中语句的问题吗?

html - flex 容器内的居中元素正在增长并溢出到顶部