我尝试仅在移动设备上使用 Bootstrap 5x 中的默认折叠功能。即使我已经设置了 CSS 媒体查询(经研究),.collapse 仍被忽略?
折叠的 DIV 项目应该在移动设备上明显折叠,并在任何宽度大于 768px 的设备上完全显示?但它在所有设备上仍然处于折叠状态。
<style>
@media screen and (min-width: 768px){
.collapse {
display: block;
height: auto !important;
visibility: visible;
}
.collapsing{
position: relative;
height: unset !important;
overflow: hidden;
}
}
</style>
<p>
<a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
EXAMPLE
</a>
</p>
<div class="collapse" id="collapseExample">
<p>
Some placeholder content for the collapse component.
</p>
</div>
关于我缺少什么有什么想法吗?
更换
.collapse
与
.collapse:not(.show)
解决了显示问题
您可以使用 mediaQueryList 对象,它使用
window.matchMedia
设置和删除 data-bs-toggle
并重新初始化元素上的可折叠元素以最初在移动设备上隐藏。
注意: 在运行片段中,由于将此 iframe 视为窗口并相应地评估媒体查询,它将被折叠。尝试全屏查看结果。
const mql = window.matchMedia("(max-width: 767px)");
const element = document.querySelector('#mobileOnlyCollapse'),
trigger = document.querySelector('.mobile-only-collapse-trigger');
let collapseInstance;
function screenTest(e) {
if (e.matches) {
/* the viewport is 767 pixels wide or less */
trigger.setAttribute('data-bs-toggle','collapse');
collapseInstance = new bootstrap.Collapse(element, {})
} else {
/* the viewport is more than 767 pixels wide */
trigger.removeAttribute('data-bs-toggle');
element.classList.add('show');
}
}
// use addEventListener change for mediaQueryList object
mql.addEventListener("change", screenTest);
//default call with mql object to run on window load
screenTest(mql);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<div>
<a role="button" class="btn btn-primary mobile-only-collapse-trigger" data-bs-toggle="collapse" href="#mobileOnlyCollapse"
aria-expanded="false" aria-controls="mobileOnlyCollapse">
Trigger button for mobile collapse
</a>
<div class="card collapse" id="mobileOnlyCollapse">
<div class="card-body" >
<span>This content should be collapsed in mobile only but shown all the time in desktop</span>
</div>
</div>
</div>