如果我在 i 标签中使用 fa-folder 并在 JavaScript 中使用 fa-folder-open,下面的简单代码就可以工作,但是如果我替换 fa-caret-right 和 fa-caret-down,它不起作用,我不明白为什么。任何帮助将不胜感激。谢谢!
<html>
<head>
<style>
.accordion {
cursor: pointer;
}
.panel {
display: none;
}
.panel.show {
display: block;
margin-left: 20px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
</head>
<body>
<p class="accordion"><i class="fa fa-folder" aria-hidden="true"></i> Building Guides</p>
<div class="panel">
<p><i class="fa fa-file-pdf-o" aria-hidden="true"></i> Accessory Structures Building Guide 2012</p>
<p><i class="fa fa-file-pdf-o" aria-hidden="true"></i> Basement Finish Building Guide 2012</p>
<p><i class="fa fa-file-pdf-o" aria-hidden="true"></i> Decks Building Guide 2012</p>
</div>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.nextElementSibling.classList.toggle("show");
this.firstChild.classList.toggle("fa-folder-open");
}
}
</script>
</body>
</html>
打开下级时,需要关闭右级。另外,我去掉了不间断的空格,并使用 CSS 渲染了相同的结果——美观但不那么烦人。
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.nextElementSibling.classList.toggle("show");
this.firstChild.classList.toggle("fa-caret-right")
this.firstChild.classList.toggle("fa-caret-down");
}
}
.fa {
width: 20px;
}
.accordion {
cursor: pointer;
}
.panel {
display: none;
}
.panel.show {
display: block;
margin-left: 20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />
<p class="accordion"><i class="fa fa-caret-right" aria-hidden="true"></i>Building Guides</p>
<div class="panel">
<p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>Accessory Structures Building Guide 2012</p>
<p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>Basement Finish Building Guide 2012</p>
<p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>Decks Building Guide 2012</p>
那是因为你拼写错误。 这是 caret 不是克拉。
有趣的是,标准 html5 details/summary 元素被定义来做到这一点,并且可以嵌入任何元素类型(例如表单)。
如果您想使用 fa 更改默认光标,请查看: 将 Font Awesome 图标设置为光标 - 这可能吗?