我希望能够使用 javasript 关闭或打开折叠。有什么想法吗?
<button data-toggle="collapse" data-target="#demo">Collapsible</button>
<div id="demo" class="collapse">
<!--Something else here-->
</div>
$("element-selector").collapse('hide')
$("element-selector").collapse('toggle')
$("element-selector").collapse('show')
https://getbootstrap.com/docs/4.0/components/collapse/#methods
<div id="searchBar" data-toggle="collapse" data-target="#filters">
Search
</div>
<div id="filters" class="collapse row">
Hello
</div>
document.getElementById("searchBar").classList.toggle("collapsed");
document.getElementById("filters").classList.remove("in");
如果有人需要 Bootstrap 5 的答案,这是一些样板代码:
import { Collapse } from 'bootstrap';
const target = document.getElementById('target'); //the element that referenced in data-bs-target
const targetCollapseInstance = new Collapse(target, {toggle: false});
const closeButton = document.getElementById('closeButton');
closeButton.addEventListener('click', () => {
targetCollapseInstance.hide();
})