以下代码是来自于网络,经过修正,目前使用正确。
可以动态响应适配。
html示例代码
<div id="carouselbox" class="layui-row">
<div class="layui-carousel" id="test10">
<div carousel-item>
<div><img class="img" style="width: 100%;" src="demo/1.jpg"></div>
<div><img class="img" style="width: 100%;" src="demo/2.png"></div>
</div>
</div>
</div>
style部分
<style type="text/css">
/*设置容器高度自适应*/
.layui-carousel>[carousel-item]>*{
height: auto;
}
.layui-carousel-ind{
margin-top: -20px;
top: auto;
bottom: 10px;
}
</style>
js部分
layui.use(['carousel', 'form'], function()
{
setTimeout(function () {
//修正高度
var fh=0;
var fw=0;
if($('.layui-carousel').length>0)
{
var imgw = $('.layui-carousel .img').length>0 ? $('.layui-carousel .img')[0].width : 0;
var imgh = $('.layui-carousel .img').length>0 ? $('.layui-carousel .img')[0].height : 0;
var imgrate=imgw/imgh;
//outerWidth clientWidth 内容 offsetWidth 包边框
if($('.layui-carousel').length>0)
{
fw=$('.layui-carousel')[0].clientWidth;
}
//修正轮播宽高为图片比例
fh=fw/imgrate;
console.log('图高'+fh);
}
//修正完成
var carousel = layui.carousel
,form = layui.form;
//图片轮播
carousel.render(
{
elem: '#test10'
,width: '100%'
//,height: 'auto'
,height: fh+'px'
,indicator:'inside'
,interval: 6000
});
//这里设置些延时,等图片加载后再取尺寸。
}, 500);
//动态适应高度
window.onresize = function () {
$('.layui-carousel div.layui-this').each(function () {
var imgH = $(this).outerHeight();
$('.layui-carousel').css('height', (imgH+1)+'px');
$(this).parent('[carousel-item]').css('height', imgH+'px');
});
};
//动态适应修正完毕
});
简单有效,少走弯路。