Tooltips这个英文词,在中文的意思是工具提示框。下文简称提示框。特指在元素周边因为特定条件而触发显示的小提示框。一般来说tooltips的提示内容就是一小段文字。
空谈误学,实干兴邦,看例子:
<style>
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">把鼠标放到这里
<span class="tooltiptext">我也用专否</span>
</div>
上面的例子中,弹出的提示框的位置并不美观,可如下进行修进。
在右侧弹出提示框
.tooltip .tooltiptext {
top: -5px;
left: 105%;
}
在左侧弹出提示框
.tooltip .tooltiptext {
top: -5px;
right: 105%;
}
在上侧弹出提示框
.tooltip .tooltiptext {
width: 120px;
bottom: 100%;
left: 50%;
margin-left: -60px; /* 使用宽度的一半(120/2 = 60)以达到居中 */
}
在下侧弹出提示框
.tooltip .tooltiptext {
width: 120px;
top: 100%;
left: 50%;
margin-left: -60px; /* 使用宽度的一半(120/2 = 60)以达到居中 */
}
上面的提示框都没有三角形小箭头的,为了更像一个对话框,可如下所示,利用伪元素为tooltip添加上小箭头。
案例1:提示框下面的箭头
.tooltip .tooltiptext::after {
content: " ";
position: absolute;
top: 100%; /* 放在弹出框的下方 */
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: black transparent transparent transparent;
}
上例详解:top: 100%则意味着放置箭头于tooltip的底边,left:50%则让箭头居中。border-width可定义箭头尺寸,如果想改变此属性,记得要同时改变margin-left的取值,从而改变保持箭头居中。为了形成箭头的感觉,因此在设置border-color时把三条边变成透明,而其中一条边留成具有可见颜色的样式;因为该元素内容为空,只有边框,因此可见的那一条边框就会呈现三角形。
案例2:提示框上面的箭头
.tooltip .tooltiptext::after {
content: " ";
position: absolute;
bottom: 100%; /* 放在弹出框的上方 */
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent black transparent;
}
案例3:提示框左侧的箭头
.tooltip .tooltiptext::after {
content: " ";
position: absolute;
top: 50%;
right: 100%; /* 放在弹出框的左侧 */
margin-top: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent black transparent transparent;
}
案例4:提示框右侧的箭头
.tooltip .tooltiptext::after {
content: " ";
position: absolute;
top: 50%;
left: 100%; /* 放在弹出框的右侧 */
margin-top: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent transparent black;
}
如下所示,利用之前说的transition属性来设置提示框的淡入效果。试试呗~
.tooltip .tooltiptext {
opacity: 0;
transition: opacity 3s;
}
.tooltip:hover .tooltiptext {
opacity: 1;
}
但是专否不建议使用淡入效果,少即是多,并不是效果越炫酷就越好,人的眼睛会被特别复杂的特效而吸引,从而影响整体的体验。纯粹简洁比酷炫是更高的境界。