使用Jquery而不是CSS的第N个子级

Nth Child using Jquery instead of CSS

本文关键字:的第 CSS Jquery 使用      更新时间:2024-06-14

我在css代码中使用nth-child,但它在IE 8中不起作用。我知道IE 8不能处理nth-child,但我需要找到一种方法让它工作。

这是我的代码:

.paypalshop .shop-groups li:nth-child(1){
  float:left;
  border: 1px solid #ccc;
  width:200px;
   }
.paypalshop .shop-groups li:nth-child(2){
  float:left;
  border: 1px solid #ccc;
  width:150px;
   }
.paypalshop .shop-groups li:nth-child(3){
  float:left;
  border: 1px solid #ccc;
  width:210px;
   }
.paypalshop .shop-groups li:nth-child(4){
  float:left;
  border: 1px solid #ccc;
  width:200px;
   }
.paypalshop .shop-groups li:nth-child(5){
  float:left;
  border: 1px solid #ccc;
  width:70px;
   }
.paypalshop .shop-groups li:nth-child(6){
  float:left;
  border: 1px solid #ccc;
  width:105px;
   }
.paypalshop .shop-groups li:nth-child(7){
  float:left;
  border: 1px solid #ccc;
  width:154px;
   }
.paypalshop .shop-groups li:nth-child(8){
  float:left;
  border: 1px solid #ccc;
  width:130px;
   }   
.paypalshop .shop-groups li:nth-child(9){
  float:left;
  border: 1px solid #ccc;
  width:220px;
   }
.paypalshop .shop-groups li:nth-child(10){
  float:left;
  border: 1px solid #ccc;
  width:220px;
   }

因此,我需要的是找到一种方法,使nth-child函数在IE8上工作。有什么jQuery方法可以让它在IE8上运行吗?

谢谢!

是使用:第n个子选择器

http://api.jquery.com/nth-child-selector/

使用css更改

http://api.jquery.com/css/

例如

$("paypalshop .shop-groups li:nth-child(2)").css("width":"150px","float":"left","border":"1px solid #ccc");

与其用jQuery更改CSS(增加80kb的页面负载和javascript对网站布局的依赖),为什么不在每个li中添加类呢?

HTML:

<ul>
    <li class="normal"><!-- 200px --></li>
    <li class="narrow"><!--- 70px --></li>
    <li class="wide"><!-- 220px --></li>
    ...
</ul>

CSS:

li { float: left; border: 1px solid #ccc; }
li.normal { width: 200px; }
li.narrow { width: 70px; }
li.wide { width: 220px; }

Imo,这是一个更清洁、更可读的解决方案,更易于维护,并为当今使用的每一个浏览器解决了您的问题。