介绍
attr()
属性函数,用来获取选择到的元素的某一 HTML
属性值, 理论上能用于所有的 CSS
属性但目前支持的仅有伪元素的 content
属性,其他的属性和高级特性目前是实验性的。
语法
attr( attribute-name <type-or-unit>? [, <fallback> ]? )
属性值解析:
attribute-name
:CSS
所引用的 HTML
属性名称
<type-or-unit>
: 所引用的属性值的单位
<fallback>
:如果 HTML
元素缺少所规定的属性值或属性值不合法,则使用 fallback
值
实用场景
使用 attr()
制作 悬浮弹框
,如图:
demo.gif
示例代码:
<template>
<!-- 操作按钮 -->
<div class="btn" data-desc="不要等到生活不困难了,才决定快乐!">摸我!</div>
</template>
<script>
export default {
name: "Attr"
};
</script>
<style scoped>
/* 按钮样式 */
.btn {
position: relative;
height: 50px;
line-height: 50px;
width: 120px;
padding: 0 10px;
margin: 200px auto 0;
background: #fff;
border: 1px solid #ddd;
color: #fff;
font-size: 16px;
text-align: center;
cursor: pointer;
background: linear-gradient(#409eff, steelblue);
border-radius: 8px;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.2);
}
/* 悬浮框样式 */
.btn:after {
content: attr(data-desc);
white-space: nowrap;
position: absolute;
top: -50px;
left: 0px;
background: #000;
border-radius: 4px;
padding: 10px;
color: #fff;
font-size: 13px;
line-height: 20px;
display: none;
}
.btn:hover:after{
display: block;
}
</style>