我有一个带有猫头鹰旋转木马和 float 元素的 Accordion 设置。 似乎高度和 float 只有在内容折叠后才有效。
无论我尝试用哪种方式为子元素(网格、 flex 、表格、内联 block )完成它 - Accordion 的行为方式相同。
打开 Accordion 后,一切都按预期进行。 这里有什么问题?
我已经设置了一个 fiddle :https://jsfiddle.net/tkvmhnu8/
HTML
<div class="accordion">
<h3 class="title"data-href="#this">Floating Content</h3>
<div class="content" id="this">
<div class="gallery">
<div class="image"></div>
<div class="image v2"></div>
<div class="image v3"></div>
<div class="image"></div>
<div class="image v2"></div>
<div class="image v3"></div>
<div class="image"></div>
<div class="image v2"></div>
<div class="image v3"></div>
</div>
</div>
</div>
CSS
* {
margin:0;
padding:0;
}
.accordion {
margin: 5px 0;
overflow:hidden;
background:teal;
padding:20px;
}
.accordion.active {
display: block
}
.accordion .title {
display: block;
position: relative;
font-size: 2rem;
line-height: 130%;
color: #FFF
}
.accordion.active .title{
overflow: show;
white-space: normal
}
.accordion.active {
opacity: 1 !important;
}
.disabled {
display:none
}
.accordion .title {
margin: 0;
cursor: pointer
}
.accordion .content {
color: #000;
overflow:hidden;
display: none;
padding:20px 0 0 0
}
.owl-item {
float: left
}
.gallery .image {
display:block;
width:400px;
height:300px;
background:rgba(225,255,255,0.8)
}
.gallery .v2 {
background:rgba(225,255,255,0.6)
}
.gallery .v3 {
background:rgba(225,255,255,0.4)
}
JS
function close_accordion_section() {
$('.accordion').removeClass('active');
$('.accordion .content').stop().slideUp(450).removeClass('open');
}
$('.accordion .title').click(function(e) {
// Grab current anchor value
var currentAttrValue = $(this).attr('data-href');
if($(this).parent().hasClass('active')) {
close_accordion_section();
} else {
close_accordion_section();
$(this).parent().addClass('active');
$('.accordion ' + currentAttrValue).addClass('open').stop().slideDown(450);
}
e.preventDefault();
});
$(".gallery").owlCarousel({
dots: false,
nav: false,
items: 4,
autoWidth:true
});
最佳答案
OwlCarousel 需要轮播元素可见才能确定其适当的宽度。
因为您的轮播元素最初不是可见的,所以子元素垂直堆叠在彼此之上,因此 slideDown()
计算出的高度非常高高。
一旦您打开它并且轮播元素变得可见,OwlCarousel 就会应用正确的宽度。这就是为什么后续尝试工作正常的原因。
解决方案 1:在页面加载时保持内容可见,以便 OwlCarousel 可以确定宽度 - JSFiddle
从 .accordion.content
中删除 display: none;
并在初始化轮播后将其隐藏
.accordion .content {
color: #000;
overflow: hidden;
/*display: none; <---- remove this */
padding: 20px 0 0 0;
}
$(".gallery").owlCarousel({ //Initialize carousel
dots: false,
nav: false,
items: 4,
autoWidth: true
});
$(".accordion .content").hide(); //Hide accordion AFTER initializing carousel
解决方案 2:自行计算并应用宽度 - JSFiddle
var totalWidth = $('.gallery > div') //Calculate the total width
.get()
.reduce((a,i)=> a + $(i).width(), 0);
$(".gallery").owlCarousel({ //Initialize owlCarousel
dots: false,
nav: false,
items: 4,
autoWidth: true
});
$(".owl-stage").width(totalWidth); //Apply the width to the stage
关于jquery - 带有 float 内容的 Accordion - 高度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55818084/