当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应该是不同的。
谢谢, 汤姆
答案 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}}