因此,我有多个div具有相同的类,并且其中的图像根据div可以为1到4,我不知道事先有多少图像,因为它们来自数据库。我如何根据div中的图像数量来给图像提供不同的类。我的HTML
<section class="feed-section">
<article class="feed-article">
<div class="question-options">
<img src="http://placehold.it/600x400">
</div>
</article>
<article class="feed-article">
<div class="question-options">
<img src="http://placehold.it/600x400">
<img src="http://placehold.it/600x400">
<img src="http://placehold.it/600x400">
<img src="http://placehold.it/600x400">
</div>
</article>
<article class="feed-article">
<div class="question-options">
<img src="http://placehold.it/600x400">
<img src="http://placehold.it/600x400">
<img src="http://placehold.it/600x400">
</div>
</article>
</section>
我的js
function imagesWidth() {
var imagesConatiner = $('.question-options').each(function (index) {
var images = $(this).children('img').length;
switch (images) {
case 1:
$('.question-options img').addClass('one')
break;
case 2:
$('.question-options img').addClass('two')
break;
case 3:
$('.question-options img').addClass('three')
break;
case 4:
$('.question-options img').addClass('four')
break;
default:
console.log(images)
}
})
};
imagesWidth()
现在的问题是,例如,它向所有图像广告多个类别,因此每三个添加一个
我想用css做它们
img.one {
width:100%
}
img.two {
width:50%
}
等等...
问题在于您要添加类的上下文,因为您将获取所有question-options
容器。尝试这个:
function imagesWidth() {
var imagesConatiner = $('.question-options').each(function (index) {
var images = $(this).children('img').length;
var self = $(this);
switch (images) {
case 1:
self.children('img').addClass('one')
break;
case 2:
self.children('img').addClass('two')
break;
case 3:
self.children('img').addClass('three')
break;
case 4:
self.children('img').addClass('four')
break;
default:
console.log(images)
}
})
};
imagesWidth()
这是一个小提琴的例子
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句