layui輪播圖根據圖片自適應(layui.carousel)
輪播圖如果固定大小,而圖片大小不相同就會導致圖片失幀,所以需要根據圖片動態調整高度和寬度。
文檔
實現原理
監聽圖片大小,根據圖片大小重置輪播圖。
html
<div class="carousel">
<div class="layui-carousel" id="carousel" lay-filter="carofilter">
<div carousel-item>
<img src="0.jpg" class="pic" style="width: 100%;height: auto"/>
<img src="1.jpg" class="pic" style="width: 100%;height: auto"/>
</div>
</div>
</div>
js
layui.use(['carousel'], function () {
var carousel = layui.carousel;
var i = 0
var ins
var width = $(".pic")[i].width * 0.5 //獲取寬度
var height = $(".pic")[i].height * 0.5 //獲取高度
ins = carousel.render({
elem: '#carousel',
width: width, //設置容器寬度
height: height,
arrow: 'hover', //始終顯示箭頭
anim: 'default', //切換動畫方式
autoplay: false
});
carousel.on('change(carofilter)', function(obj){ //監聽輪播
i = obj.index
width = $(".img")[i].width
height = $(".img")[i].height
ins.reload({ //重置輪播
elem: '#carousel',
width: width, //設置容器寬度
height: height,
arrow: 'hover', //始終顯示箭頭
anim: 'default', //切換動畫方式
autoplay: false
});
});
});
效果
下面兩張圖高度不一致,可自動調整。