【问题标题】:Check if <ul> has less than 3 <li> items and apply CSS style检查 <ul> 是否少于 3 个 <li> 项目并应用 CSS 样式
【发布时间】:2015-03-03 20:02:13
【问题描述】:

当 UL 内的项目少于 3 li 时,我需要更改 ul li 项目的宽度。这是我创建的,但它不能正常工作,你能帮我解决它吗?

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

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

谢谢, 汤姆

【问题讨论】:

  • 您可能还需要发布您的 html,以便我们查看您的 html 的结构,并知道 .products 是什么。
  • 这听起来像是 XY 问题。 meta.stackexchange.com/questions/66377/what-is-the-xy-problem 请发布您的 HTML 和 CSS。您可能不需要 JavaScript。
  • $($this).css('width', '29%'); 应该是$('ul.products').css('width', '29%');
  • 你应该得到一个错误说Error: '$this' is undefined

标签: jquery css wordpress woocommerce


【解决方案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

尝试在ul 中添加另一个li 元素,样式将不起作用

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

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

现在您可以在ul 内设置li's 元素的样式,前提是li's 少于3 个而没有javascript

编辑

小于或等于 3 li's :

 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;

}

小于或等于 4 li's :

 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;

}

【讨论】:

  • 检查第二个现场演示,如果一个元素我很确定它不会失败!
  • 我根据之前的答案写了我的评论...现在可以了:-)
  • 非常好的解决方案,但是如果我希望它小于 3 或等值怎么办?
  • 少于 3 个它仍然会应用你的 css
  • 只需测试小提琴中的演示,您会发现如果添加超过 2 li 会失败,但如果添加少于 3 li 则不会失败
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
  • 2022-01-19
  • 2011-08-06
  • 2013-12-01
  • 2018-06-13
  • 2018-07-30
  • 2011-08-04
相关资源
最近更新 更多