首页 > 解决方案 > 可折叠按钮在移动设备上不起作用

问题描述

我正在制作一个简单的网站,并有三个可折叠的按钮。每个都显示网站本身的代码。它们在 PC 上单击时打开,但在移动设备上单击时不打开。所发生的只是按钮被突出显示。这是我正在使用的代码。

Javascript:

  <script>
var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}
</script>

这是CSS:

.collapsible {
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: center;
    outline:none;
    font-size: 15px;
    font-family: sans-serif;

}

.active, .collapsible:hover {
    background-color: rgb(7, 6, 6);
    cursor: pointer;
}

.content {
    padding: 18px;
    display: none;
    overflow: hidden;
    cursor: pointer;
}

这是html:

<body>
<button type="button" class="collapsible">CSS</button>
<div class="content">
     contents
</div>
<button type="button" class="collapsible">HTML</button>
<div class="content">
     contents2
</div>
<button type="button" class="collapsible">JavaScript</button>
<div class="content">
     contents3
</div>
</body>

我尝试向 Javascript 添加一个 touchstart 处理程序,但这不起作用。谢谢你的帮助。如果这是一个明显的答案,我深表歉意,我是网站新手。

标签: javascriptjqueryhtmlcss

解决方案


您的 HTML 结构已损坏。您忘记打开第二个 div 元素。

所以你的 HTML 应该是:

<body>
  <button type="button" class="collapsible">CSS</button>
  <div class="content">
       contents
  </div>
  <button type="button" class="collapsible">HTML</button>
  <div class="content">
       contents2
  </div>
  <button type="button" class="collapsible">JavaScript</button>
  <div class="content">
       contents3
  </div>
</body>

我为你的字体添加了一些颜色:

.collapsible {
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: center;
    outline:none;
    font-size: 15px;
    font-family: sans-serif;
    color: #000000;
}

.active, .collapsible:hover {
    background-color: rgb(7, 6, 6);
    cursor: pointer;
    color: #ffffff;
}

.content {
    padding: 18px;
    display: none;
    overflow: hidden;
    cursor: pointer;
}

jsfiddle上的工作示例


推荐阅读