检查<ul>是否少于3个<li>项并应用CSS样式</li> </ul>

时间:2015-03-03 20:02:14

标签: jquery css wordpress woocommerce

当UL内部的物品少于3件时,我需要更改ul li物品的宽度。这就是我创建的,但是它无法正常工作,你可以帮我修复它吗?

jQuery(document).ready(function($) {
  if ($('ul.products li').length <= 3) {
  $($this).css('width', '29%'); 
}})

该网站为http://www.demo.simplexweb.dk/shopdemo1/。它与3个产品的部分有关。如果有人添加了新产品,那么css应该是不同的。

谢谢, 汤姆

1 个答案:

答案 0 :(得分:1)

你可以用css这样做:

 li:nth-of-type(1):nth-last-of-type(2),
 li:nth-of-type(2):nth-last-of-type(1){width: 50%;}

如果它是第一个类型,倒数第二个类型,这意味着如果这两个条件为真,那么这个类型只有两个元素,然后你可以申请width: 50%;

<强> Live Demo

尝试向li添加其他ul元素,但样式无效

这正是您的任务所需要的:

li:nth-of-type(1):nth-last-of-type(2),
 li:nth-of-type(2):nth-last-of-type(1){

    width: 50%;
    background-color: black;
}

li:only-of-type{  // this to still apply the style if the element is only of it's type

    width: 50%;
    background-color: black;

}

<强> Live Demo

现在,只有当li's少于ul而没有任何li's

时,您才能在javascript内设置li's元素的样式

修改

少于或相当于3 li:nth-of-type(1):nth-last-of-type(3), li:nth-of-type(3):nth-last-of-type(1), li:nth-of-type(2):nth-last-of-type(2){width: 50%; background-color: black;} li:nth-of-type(1):nth-last-of-type(2), li:nth-of-type(2):nth-last-of-type(1){width: 50%; background-color: black;} li:only-of-type{ width: 50%; background-color: black; }

li's

少于或等于4 li:nth-of-type(1):nth-last-of-type(4), li:nth-of-type(2):nth-last-of-type(3), li:nth-of-type(3):nth-last-of-type(2), li:nth-of-type(4):nth-last-of-type(1){width: 50%; background-color: black;} li:nth-of-type(1):nth-last-of-type(3), li:nth-of-type(3):nth-last-of-type(1), li:nth-of-type(2):nth-last-of-type(2){width: 50%; background-color: black;} li:nth-of-type(1):nth-last-of-type(2), li:nth-of-type(2):nth-last-of-type(1){width: 50%; background-color: black;} li:only-of-type{ width: 50%; background-color: black; }

{{1}}