网页网站您现在的位置是:首页 > 博客日志 > 网页网站

你还在用后台代码实现隔行变色?已经OUT了!

<a href='mailto:'>微wx笑</a>的头像微wx笑 2019-06-28网页网站 23 0关键字: CSS  伪类选择器  

自从有了CSS3,隔行变色的效果又多了一种实现方案,CSS伪类选择器的强大,还不止于此。

无知人生,ivu4e.com,ivu4e.cn

自从有了CSS3,隔行变色的效果又多了一种实现方案,CSS伪类选择器的强大,还不止于此。YJn无知

例如下图的编号:YJn无知

image.pngYJn无知

实现方式:YJn无知

image.pngYJn无知


YJn无知

:nth-child(even) 控制偶数样式YJn无知


YJn无知

:nth-child(odd)控制奇数样式YJn无知


YJn无知

:nth-child(2n+1)控制2n+1行样式YJn无知


YJn无知

语法:YJn无知


YJn无知

:nth-child(an+b)YJn无知

下面就把CSS3标准中nth-child()用法大致介绍给大家:YJn无知


YJn无知

CSS3伪类选择器:nth-child()YJn无知

简单的归纳下nth-child()的几种用法。YJn无知


YJn无知

第一种:简单数字序号写法YJn无知

:nth-child(number)YJn无知


YJn无知

直接匹配第number个元素。参数number必须为大于0的整数。YJn无知


YJn无知

例子:YJn无知


YJn无知

li:nth-child(3){background:blue;}YJn无知

第二种:倍数写法YJn无知

:nth-child(an)YJn无知


YJn无知

匹配所有倍数为a的元素。其中参数an中的字母n不可缺省,它是倍数写法的标志,如3n、5n。YJn无知


YJn无知

例子:YJn无知


YJn无知

li:nth-child(3n){background:red;}YJn无知


YJn无知

第三种:倍数分组匹配YJn无知

:nth-child(an+b) 与 :nth-child(an-b)YJn无知


YJn无知

先对元素进行分组,每组有a个,b为组内成员的序号,其中字母n和加号+不可缺省,位置不可调换,这是该写法的标志,其中a,b均为正整数或0。如3n+1、5n+1。但加号可以变为负号,此时匹配组内的第a-b个。(其实an前面也可以是负号,但留给下一部分讲。)YJn无知


YJn无知

例子:YJn无知


YJn无知

li:nth-child(3n+1){background:red;}YJn无知


YJn无知

li:nth-child(3n+5){background:blue;}YJn无知


YJn无知

li:nth-child(5n-1){background:yellow;}YJn无知


YJn无知

li:nth-child(3n±0){background:green;}YJn无知


YJn无知

li:nth-child(±0n+3){background:orange;}YJn无知


YJn无知

第四种:反向倍数分组匹配YJn无知

:nth-child(-an+b)YJn无知


YJn无知

此处一负一正,均不可缺省,否则无意义。这时与:nth-child(an+1)相似,都是匹配第1个,但不同的是它是倒着算的,从第b个开始往回算,所以它所匹配的最多也不会超过b个。YJn无知


YJn无知

例子:YJn无知


YJn无知

li:nth-child(-3n+8){background:red;}YJn无知


YJn无知

li:nth-child(-1n+8){background:blue;}YJn无知


YJn无知

第五种:奇偶匹配YJn无知

:nth-child(odd) 与 :nth-child(even)YJn无知


YJn无知

分别匹配序号为奇数与偶数的元素。奇数(odd)与(2n+1)结果一样;偶数(even)与(2n+0)及(2n)结果一样。YJn无知


YJn无知

作者观点:表格奇偶数行定义样式就可以写成YJn无知

.table > tr:nth-child(even) > td {background-color: #f00;} (偶数行)YJn无知

.table > tr:nth-child(odd) > td {background-color: #c00;} (奇数行)YJn无知


YJn无知

jQuery中用此方法可以实现条纹效果:YJn无知

$(“table tr:nth-child(even)”).addClass(“hangbg”);YJn无知

even 可以换成别的参数,上面介绍的五种情况都可以。YJn无知

后面的addClass(“hangbg”) hangbg 是个CSS class名称。YJn无知


YJn无知


YJn无知

无知人生,ivu4e.com,ivu4e.cn

本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/web/2019-06-28/19.html

很赞哦! () 有话说 ()

相关文章