javascript - 可折叠按钮在移动设备上不起作用
问题描述
我正在制作一个简单的网站,并有三个可折叠的按钮。每个都显示网站本身的代码。它们在 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 处理程序,但这不起作用。谢谢你的帮助。如果这是一个明显的答案,我深表歉意,我是网站新手。
解决方案
您的 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上的工作示例
推荐阅读
- python - django 无法向数据库提交评论
- javascript - 注册表格以提交到不同的位置
- laravel - Laravel:试图获得非对象的属性“街道”
- android - FirebaseUI 导致 DexException 多个 Dex 文件
- ios - 多次重新加载 TableView Swift
- plugins - 为什么每次都为我的 word 插件获得“需要许可”?
- batch-file - 查找重复的数量并批量复制该行
- node.js - Neutrinojs/vue 项目:从根文件夹导入 vue 文件/模板
- php - 尝试解析文件的 SimpleXLSX 错误
- angular - 如何使用 aot 和桶构建自定义 angular 6 库模块