将一个类添加到一系列元素中会有什么好处,具体取决于它们中有多少元素存在?
所以在这种情况下,如果有两个或更少的项目,该类是“一半” - 如果小于8,则应该应用“季度”类。
根据节中有多少“项目”,有没有办法添加/删除一个类?
<section>
<div class="item half"> 1 </div>
<div class="item half"> 2 </div>
</section>
<section>
<div class="item quarter"> 1 </div>
<div class="item quarter"> 2 </div>
<div class="item quarter"> 3 </div>
<div class="item quarter"> 4 </div>
<div class="item quarter"> 5 </div>
</section>
答案 0 :(得分:3)
您可以随时获取元素的数量,例如
var elems = document.querySelectorAll(".item");
var count = elems.length;
if(count < 2) {
// add class half
} else if (count < 8) {
// add class quarter
}
答案 1 :(得分:2)
你可以试试这个:
$(document).ready(function(){
$('section').each(function(i, sect){
var itemsInSection = $(sect).children('.item');
var count = itemsInSection.length;
if(count < 3){
itemsInSection.addClass('half');
}else if(count < 8){
itemsInSection.addClass('quarter');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div class="item half"> 1 </div>
<div class="item half"> 2 </div>
</section>
<section>
<div class="item quarter"> 1 </div>
<div class="item quarter"> 2 </div>
<div class="item quarter"> 3 </div>
<div class="item quarter"> 4 </div>
<div class="item quarter"> 5 </div>
</section>