gpt4 book ai didi

JavaScript 在展开和折叠时在 Accordion 上切换图标

转载 作者:行者123 更新时间:2023-11-29 15:55:57 25 4
gpt4 key购买 nike

我有一个可以展开和折叠的 Accordion 。这是代码:https://jsfiddle.net/96jqo3ba/2/ .我想使用 FontAwesome 图标类来表示 Accordion 选项卡何时展开和折叠。这是我想使用的两个 fontAwesome 类:

<i class="fas fa-plus" /i>
<i class="fas fa-minus" /i>

在 cshtml 中,我添加了 <i class="fas fa-plus"/i> .我的问题是,在我的 Jquery 脚本中,如何在 <i class="fas fa-plus" /i> 之间切换和 <i class="fas fa-plus" /i> Accordion 选项卡何时展开和折叠?

J查询:

var coll = document.getElementsByClassName("accordion-toggle");
for (var i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function(evnt) {
const currClassList = evnt.currentTarget.classList;
if (currClassList.contains('collapsed')) {
evnt.currentTarget.classList.remove("collapsed");
var content = evnt.currentTarget.nextElementSibling;
content.style.maxHeight = null;
} else {
for (var j = 0; j < coll.length; j++) {
coll[j].classList.remove("collapsed")
coll[j].nextElementSibling.style.maxHeight = null;
}
this.classList.toggle("collapsed");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
}
});
}

最佳答案

根据您当前的设置,您可以在标记中添加彼此相邻的 fa-plusfa-minus 元素,然后添加以下 css 以隐藏/根据 collapsed 类是否存在显示它们:

HTML:

<h2 class="accordion-toggle"><i class="fa fa-plus pull-right"></i><i class="fa fa-minus pull-right"></i><button>
Open Collapsible
</button></h2>
<div id="anyId" class="collapse">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<h2 class="accordion-toggle"><i class="fa fa-plus pull-right"></i><i class="fa fa-minus pull-right"></i><button>
Open Section 1
</button></h2>
<div class="collapse">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

CSS:

.accordion-toggle {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}

.collapsed, .accordion-toggle:hover {
background-color: #555;
}

.collapse {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}

.fa-minus {
display: none;
}

.collapsed .fa-minus {
display: block;
}

.collapsed .fa-plus {
display: none;
}

关于JavaScript 在展开和折叠时在 Accordion 上切换图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57949619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com