【问题标题】:Select div with random class选择具有随机类的 div
【发布时间】:2014-08-27 07:34:22
【问题描述】:

我在我的单页上使用 iosslider。 我需要从 '.wp-pic' 收集所有 img src 并将它们放到滑块背景 url 中。 所以我有什么:

带有 WP 图片的滑块框架和 DIV:

<div class='my-slider large-9 columns'>
  <div class='sliderContainer'>
    <div class='iosSlider'>
      <div class='slider'>

      </div>
    </div>
  </div>
</div><!--/.slider-->

<div class='wp-pic'>
  <?php if(have_posts()) : ?> 
    <?php while(have_posts()) : the_post(); ?> 
       <?php the_content(); ?>
    <?php endwhile; ?>
  <?php endif; ?>
</div>

/* SLIDER SETTINGS
=============================================*/
.sliderContainer{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
}
.iosSlider{
  position: relative;
  top: 0;
  left: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
}
.iosSlider .slider{
  width: 100%;
  height: 100%;
}
.iosSlider .slider .item{
  float: left;
  width: 100%;
  height: 100%;
}

// REMOVE PICTURES PUSHED BY WP AND PUT THEM TO THE IOSSLIDER
  $('.wp-pic').find('img').each(function(){
    var photoSrc  = $(this).attr('src'),
        photoImg  = '<img src="' + photoSrc + '">',
        numbClass = Math.round(Math.random() * 15);
    $('.slider').append('<div class="item photo-template' + numbClass + '">' + photoImg + '</div>');
    $('.wp-pic').remove();
  });

  $('.item').find('img').each(function(){
    var x = $(this).attr('src');
    $('.slider').find('div:contains(photo-template)').each(function(){ 
      $(this).css({
        'background-image'   :'url(' + x + ')',
        'background-size'    :'contain',
        'background-position':'center',
        'background-repeat'  :'no-repeat'
      });
    });
    $(this).remove();
  });

如何选择每个类的“照片模板”并将其放置在背景收集的 src 中?

FIDDLE

【问题讨论】:

    标签: javascript jquery css wordpress jquery-ui-slider


    【解决方案1】:

    你不需要不同的班级来做你想做的事。

    你只需一个循环就可以得到它。只需遍历每个 img,然后更改它的父 css。

    $('.item').find('img').each(function(){
        var x = $(this).attr('src');
        $(this).parent().css({
            'background-image'   :'url(' + x + ')',
            'background-size'    :'contain',
            'background-position':'center',
            'background-repeat'  :'no-repeat'
        });
        $(this).remove();
    });
    

    看看我根据你的FIDDLE制作的。

    【讨论】:

    • 我的一个建议是使用this.src 而不是jQuery 的attr() 方法。
    • @DavidThomas 我认为继续使用 jQuery 会更好。混合使用 jQuery 和纯 javascript 可能会有点混乱。
    • 嗯,这是你的答案和不必要的复杂性,很公平。
    【解决方案2】:

    $(".photo-template") 上使用 jQuery.each(),它将返回具有该类的每个元素。

    格式:

    $.each( $(".photo-template"), function(el, i) {
      // do something with $(el).find("img").attr("src")
    };
    

    【讨论】:

    • 我已经这样做了,因为你可以看到班级照片模板每次看起来都不一样 - 因为我为它生成了一个 numberClass。我没有.photo-template,我有一些看起来像“photo-template + Math.round(Math.random() * 15)”的随机类
    猜你喜欢
    • 2015-04-02
    • 2012-06-26
    • 2021-09-09
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多