CSS属性之attr()

CSS函数attr()是用来获取被选中元素的属性值,并且在样式文件中使用。它也可以用在伪类元素里,在伪类元素里使用,它得到的是伪元素的原始元素的值。

attr()函数可以和任何CSS属性一起使用,但是除了content外,其余都还是试验性的(简单说就是不稳定,浏览器不一定支持)。

那具体怎么用呢,给大家举个栗子,前段时间刚好用到的,给按钮实现提示功能,就是鼠标放上去后,出来个小提示:

<div class="wrap">
  <a href="#" class="btn" data-tip="点击作答">一个按钮</a>
</div>

 

 

.btn {
  display: inline-block;
  padding: 5px 20px;
  border-radius: 4px;
  background-color: #6495ed;
  color: #fff;
  font-size: 14px;
  text-decoration: none;
  text-align: center;
  position: relative;
}
.btn::before {
  content: attr(data-tip);
  width: 80px;
  padding: 5px 10px;
  border-radius: 4px;
  background-color: #000;
  color: #ccc;
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translate(-50%);
  text-align: center;
  opacity: 0;
  transition: all .3s;
}
.btn::after {
  content: '';
  border: 8px solid transparent;
  border-top: 8px solid #000;
  position: absolute;
  top: -3px;
  left: 50%;
  transform: translate(-50%); 
  opacity: 0;
  transition: all .3s;
}
.btn:hover::before {
  top: -40px;
  opacity: 1;
}
.btn:hover::after {
  top: -13px;
  opacity: 1;
}

 

 

 

 当然attr()还可以获取更多的其他属性,比如a标签里的href属性等,更多的用法大家自行尝试吧。

posted @ 2018-01-02 17:01  铭绘  阅读(10978)  评论(0编辑  收藏  举报