javascript - 选择具有随机类的 div

标签 javascript jquery css wordpress jquery-ui-slider

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

带有 WP 图片的 slider 框架和 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();
  });

我如何选择每个类(class)的“照片模板”并将收集的 src 放在他们的背景上?

FIDDLE

最佳答案

你不需要有不同的类来做你想做的事。

而且你只需要一个循环就可以得到它。只需遍历每个 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我根据你的做了。

关于javascript - 选择具有随机类的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600089/

相关文章:

html - 父子元素的css定位

javascript - 如何使用javascript发送邮件

javascript - onClick 获取被点击按钮的ID

javascript - 使用 javascript 将数据插入 Google Sheets API

javascript - 淡入淡出的图像弄乱了内联 block 样式的 div

javascript - jQuery - 必须按下按钮两次或更多次才能使功能保持不变

javascript - Codeigniter 2.1,Jquery - 500 内部服务器错误

javascript - 第一次点击时日期选择器不显示

javascript - 如何使用 jQuery 从 DOM 元素创建 JavaScript 变量

html - 删除图像周围的空白 - CSS