html代码:
<div class="layui-carousel" id="banner" lay-filter="banner">
<div carousel-item="">
<div class="banner-item"><img src="https://img.zcool.cn/community/01c7025690836d32f87574be8473ba.jpg"></div>
<div class="banner-item"><img src="https://img.zcool.cn/community/0111e75690836e32f87574be3c0e51.jpg"></div>
<div class="banner-item"><img src="https://img.zcool.cn/community/0185b3554543b50000019ae9c7ed0e.jpg"></div>
<div class="banner-item"><img src="https://img.zcool.cn/community/017600555ec67b0000009c5021f1b7.jpg"></div>
<div class="banner-item"><img src="https://img.zcool.cn/community/016303555ec6c50000009af0be03e5.jpg"></div>
</div>
</div>
js代码
<script> layui.use(['jquery','carousel'], function(){
var $ = layui. $
var carousel = layui.carousel //轮播模块
var W = $('#banner').width();//获取容器的宽度
var screenImage = $('#banner img');//获取轮播图DOM
var theImage = new Image(); theImage.src = screenImage.attr("src");
var b = theImage.width/theImage.height;//获取轮播图的原始宽高比例
//常规轮播
carousel.render({
elem: '#banner'
,width: '100%'
,height: (W/b).toString()+"px"
,arrow: 'always'
});
$(window).resize(function () { window.location.reload() }) });
</script>
css代码
.banner-item img{width:auto;height:auto; max-width:100%; max-height:100%;}
这个实现方法有一点不好的地方,就是窗口宽度变化会引起重载,前端访问能明显感觉到。兼容性暂时没有考虑。
期待有更好更平滑的方法。
网友评论