css3 学习之 attr()

Fork Me On Github
zodream 编程技术 2018年12月

说明

接受两个参数, 第一个参数时主元素的属性名,可以跟转化类型,第二个是默认值,

例如:

css
   
a::before {
    color: attr(data-color color, red);
}
123

字符串拼接

css
   
a::before {
    content: "Hi " attr(data-hover);
}
123

一个切换例子

css
                                    
.box {
    font-size: 55px;
    overflow: hidden;
    position: relative;
}
.box span {
    display: inline-block;
    position: relative;
    transition: transform 0.3s;
}
.box span:first-child {
    color: #666;
}
.box span:nth-child(2) {
    color: #daa520;
}
.box span:nth-child(2)::before {
    bottom: 105%;
    color: #666;
}
.box span:first-child::before {
    top: 105%;
    color: #daa520;
}
.box span:first-child::before,
.box span:nth-child(2)::before {
    position: absolute;
    content: attr(data-hover);
}
.box:hover span:first-child {
    transform: translate3d(0, -105%, 0);
}
.box:hover span:nth-child(2) {
    transform: translate3d(0, 105%, 0);
}
123456789101112131415161718192021222324252627282930313233343536
html
      

<div class="box">
    <span data-hover="my">my</span>
    <span data-hover="friend">friend</span>
</div>
123456
点击查看全文
0 603 0