解决nth-child(n)属性在IE8浏览器中兼容性问题

【前言】

    学生提问:nth-child(n)属性在IE8浏览器失效方案?

【案例】

   在项目中经常用到nth-child(n)属性,如下所示

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>demo测试</title>
	<style type="text/css">
		*{margin: 0;padding: 0}
		.parent{
			width: 600px;
			height: 300px;
			border: 1px solid red;
			margin: auto;
		}
		.parent div{
			display: inline-block;
			width: 100px;
			height: 100px;
			*display: inline;
			zoom:1;
		}
		.parent div:nth-child(1){
			background-color: red;
		}
		.parent div:nth-child(2){
			background-color: blue;
		}
		.parent div:nth-child(3){
			background-color: green;
		}
	</style>
</head>
<body>
<div class="parent">
	<div></div>
	<div></div>
	<div></div>
</div>
</body>
</html>

   该属性却在IE8浏览器中出现兼容性问题,可以使用以下方式处理在IE8中兼容性 

【方案】

(1)方案一

这里我首先想到的一个简单的解决方案为CSS兄弟选择器,因为IE支持first-child与last-child,所以我可用兄弟选择器去解决。

缺点:子元素过多时,不易操作

<style type="text/css">
		.parent div:first-child{
			background-color: red;
		}
		.parent div:first-child+div{
			background-color: blue;
		}
		.parent div:first-child+div+div{
			background-color: green;
		}
</style>

 (2)方案二

   使用jQuery中的选择器:nth-child代替,和css3中的使用规则相同

:nth-child(odd)用于匹配奇数子元素

:nth-child(even)用于匹配偶数子元素

:nth-child(n)用于匹配第n个元素

:nth-child(an)用于匹配倍数为a的元素,如3n、5n…

   可以是一个公式,如:nth-child(3n+1)匹配第1、第4、第7…个元素

:nth-child(-n+3)匹配前3个元素

:nth-child(-3n+8)匹配第8、第5、第2个元素

  

.

猜你喜欢

转载自570109268.iteye.com/blog/2413348