【问题标题】:How to take the 'src' from an image in a post and make it a background image just for that post with jquery when there's multiple posts on page?当页面上有多个帖子时,如何从帖子中的图像中获取“src”并使其成为该帖子的背景图像?
【发布时间】:2017-07-08 21:26:58
【问题描述】:

对不起,如果这个问题是满口的。基本上这就是我想要做的:
这是 html 标记:

<article class="swiper-slide">
    <div class="image"></div>
    <div class="copy">
        <h1 class="index-name"><span>Jean-Michel Basquiat</span></h1>
        <div class="article-summary">
            <img src="img/profiles/profile_jbasquiat.jpg"/>
            <h2>Preview Copy</h2>
            <a href="#" class="read-more serif">read more</a>
        </div>
    </div>
</article>

<article class="swiper-slide">
    <div class="image"></div>
    <div class="copy">
        <h1 class="index-name"><span>Lorraine Vivian Hansberry</span></h1>
        <div class="article-summary">
            <img src="img/profiles/profile_lhansberry.jpg"/>
            <h2>Preview Copy</h2>
            <a href="#" class="read-more serif">read more</a>
        </div>
    </div>
</article>

所以我想要做的是将src 用于每个div 中的img 元素与.article-summary,然后将其作为相关div 与该类的背景图像.image 以上。现在,我过去曾成功使用此脚本,但仅当我在每个帖子的单独页面上时。它针对所有内容,因此我为所有背景图像获得了相同的图像:

var img = $('.article-summary img').attr('src');
$('.image').css('background-image', 'url('+img+')');

我环顾四周,在另一个 stackoverflow post 上找到了这个脚本,但我也无法让它工作。我的图像只是显示为空白。我不是 JavaScript 工作逻辑方面的专家,所以我想在这里问问专家。

关于如何使它工作的任何建议?

【问题讨论】:

  • 在 jsbin 或 codepen 上分享你的例子,它应该可以工作,你可能会遗漏一些东西

标签: javascript jquery css image background-image


【解决方案1】:
$('.swiper-slide').each(function(){

  var img = $(this).find('.article-summary img').attr('src');
  $(this).find('.image').css('background-image', 'url('+img+')');
});

您需要为每张幻灯片都这样做 - 类似上面的方法应该可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 2016-05-04
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 2013-07-27
    • 2014-06-15
    • 2020-11-06
    相关资源
    最近更新 更多