调整图像大小以使其完美地适合幻灯片,问题仍然是用 for 循环将 CSS 代码替换为我的图像

resizing image so it fits into slide perfectly, still the issue is replacing css code with my image with for-loop

本文关键字:图像 循环 for 仍然是 代码 我的 替换 问题 CSS 幻灯片 完美      更新时间:2023-09-26

我正在使用猫头鹰轮播,我拥有的默认代码具有漂亮的颜色背景。 但我想为每张幻灯片使用不同的图像,而不是彩色背景。我在插入文本时插入了一个图像,但是图像太大,整个东西都崩溃了。你能帮我这个吗?这里是轮播代码

<div class="wrapper-with-margin">
<div id="owl-demo" class="owl-carousel">
{% for import in mustSee %}
     <div class="owl" style="white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis; font-size:12px;">{{import.title}}
    <img src="{{import.get_image_url}}" /></div>
{% endfor %}
</div>
</div>

显示文本,但问题是图像,图像需要是div标签的背景。但是问题是我正在使用 for loop 为每张幻灯片显示不同的图像,我不能像在 css 中那样直接更改背景。而在 css 中,

#owl-demo .owl-item > div{
  background : #42bdc2;
  text-align: center;
  padding:50px 0px;
  margin:3px;
  color: white;
  font-size:32px;
  border:1px white;
}

而不是

 background : #42bdc2;

当然,我希望这是<img src="{{import.get_image_url}}" />,因为我正在使用 for 循环,我也需要考虑这一点。 如何用此图像替换彩色背景?

您可以使用内联css来更改background-image属性。

<div style="background-image: url('{{import.get_image_url}}')">

确保同时设置背景属性。像这样的东西,但考虑到您的元素和图像尺寸:

div {
  background: transparent url('fallback.jpg') no-repeat scroll center center / cover;
}

已更新以反映您的特定元素。

在你的css文档中,你需要你的background规则和你的回退图像(我假设.owl是你的类名):

.owl {
    background: #42bdc2 url('path/tp/fallback.jpg') no-repeat scroll center center / cover;
    text-align: center;
    padding:50px 0px;
    margin:3px;
    color: white;
    font-size:32px;
    border:1px white;
}

现在,对于您的内联样式(注意:您不想将<img src="">用于 css 规则,您只想像往常一样更新background-image):

<div class="owl" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size:12px; background-image: url('{{import.get_image_url}}')"></div>

请注意语法 - background-image: url("url-goes-here"); ; 您显然会url-goes-here替换为{{import.get_image_url}},如示例中所示。

如果我理解正确了你的问题,这就是你想做的简短:

使用 img-src 作为div 的 bg

您可以使用jquery轻松完成此操作

$(".your-div").each(function(){
  var imgSrc = $(this).find(".your-img-tag").attr("src");
  $(this).css("background","url('"+imgSrc+"')");
});
如果你不想在img

标签中显示你的图像,你可以隐藏它,或者有一个干净的代码,把那个img-url放入你的div data-src并使用以下代码

$(".your-div").each(function(){
  $(this).css("background","url('"+$(this).attr("data-src")+"')");
});