我在我的单页上使用 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 放在他们的背景上?
最佳答案
你不需要有不同的类来做你想做的事。
而且你只需要一个循环就可以得到它。只需遍历每个 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/