我有一个bootstrap 4轮播:
<section id="carousel-landing" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
<h1>Title 1</h1>
<p>text 1</p>
<img src="img.jpg">
</div>
<div class="carousel-item">
<h1>Title 2</h1>
<p>text 2</p>
<img src="img.jpg">
</div>
<div class="carousel-item">
<h1>Title 3</h1>
<p>text 3</p>
<img src="img.jpg">
</div>
</div>
<a class="left carousel-control" href="#carousel-landing" role="button" data-slide="prev">
<span class="icon-prev" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-landing" role="button" data-slide="next">
<span class="icon-next" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</section>
#carousel-landing,.carousel-inner和.carousel-item都将高度设置为100%。 h1,p和img彼此堆叠在一起。如果每张幻灯片上的h1和p具有不同的高度,如何设置每个图像的高度以填充视口的其余部分?
我试过这个:
$(document).ready(imgResize);
$(window).on('resize',imgResize);
function imgResize() {
$('#carousel-landing .carousel-item').each(function() {
var dynamic_height = ($('#carousel-landing .carousel-item').height() - $('#carousel-landing .carousel-item h1').outerHeight() - $('#carousel-landing .carousel-item p').outerHeight()) - 40;
$('#carousel-landing .carousel-item img').css("height", dynamic_height + "px");
});
}
但这仅针对第一张幻灯片,并将其余图片设置为与第一张图片具有相同的高度。在浏览器调整大小时,它仅适用于第一张幻灯片,当下一张幻灯片滑入并调整浏览器大小时,图像突然调整为100%高度,就像h1和p元素甚至不存在一样
答案 0 :(得分:0)
您必须从carousel-item
div的高度减去文字的高度,在此处:https://jsfiddle.net/aufbhkdv/37/
$(".carousel-item").each(function(){
var carouselHeight = $(this).outerHeight(),
textHeight = $(this).children("h1").outerHeight() + $(this).children("p").outerHeight();
$(this).children("img").height(carouselHeight - textHeight);
});
答案 1 :(得分:0)
如果你想把你的内容填充到100%填充图像,你必须&#34; crop&#34;你的图片保留图像比例,图像不会拉伸
当您的幻灯片可见时(您必须有一些事件要通知此事)
您必须在展示完所有幻灯片后对所有幻灯片执行此操作(以便能够衡量所有内容)
但是如果你想浏览器自动为你做,那么你可以使用background-size:cover;
只需获取图像src并将div替换为背景设置为此src的div并将此div设置为填充左侧空间并设置背景大小以覆盖
$(".carousel-item").each(function(){
let carouselHeight = $(this).outerHeight();
let textHeight = $(this).children("h1").outerHeight() + $(this).children("p").outerHeight();
let src=$(this).children("img").attr('src');
$(this).append('<div style="background:url('+src+') center center;background-size:cover;width:100%;height:'+(carouselHeight-textHeight)+'px"></div>');
$(this).children("img").remove();
});