实现 Tooltip
大约 1 分钟
实现 Tooltip
1. 基本 Tooltip
本文直接参考 Spectre.css 的实现,其示例如下。
查看源码
<button class="action-button primary tooltip tooltip-left" data-tooltip="提示">左边</button>
<button class="action-button primary tooltip tooltip-right" data-tooltip="提示">右边</button>
<button class="action-button primary tooltip" data-tooltip="提示">上面</button>
<button class="action-button primary tooltip tooltip-bottom" data-tooltip="提示">下面</button>
Scss 代码:
// Tooltips
$dark-color: rgb(48, 55, 66);
$light-color: #fff;
$border-radius: .2rem;
$unit-1: .2rem;
$unit-2: .4rem;
$corner-size: 5px;
.tooltip {
position: relative;
&::after {
background: rgba($dark-color, .95);
border-radius: $border-radius;
bottom: 100%;
color: $light-color;
content: attr(data-tooltip);
display: block;
left: 50%;
max-width: 60vw;
opacity: 0;
overflow: hidden;
padding: $unit-1 $unit-2;
pointer-events: none;
position: absolute;
text-overflow: ellipsis;
transform: translate(-50%, $unit-2);
transition: opacity .2s, transform .2s;
white-space: pre;
z-index: 300;
}
&:focus,
&:hover {
&::after {
opacity: 1;
transform: translate(-50%, -$unit-1);
}
&::before {
opacity: 1;
}
}
&[disabled],
&.disabled {
pointer-events: auto;
}
&.tooltip-right {
&::after {
bottom: 50%;
left: 100%;
transform: translate(-$unit-1, 50%);
}
&:focus,
&:hover {
&::after {
transform: translate($unit-1, 50%);
}
}
}
&.tooltip-bottom {
&::after {
bottom: auto;
top: 100%;
transform: translate(-50%, -$unit-2);
}
&:focus,
&:hover {
&::after {
transform: translate(-50%, $unit-1);
}
}
}
&.tooltip-left {
&::after {
bottom: 50%;
left: auto;
right: 100%;
transform: translate($unit-2, 50%);
}
&:focus,
&:hover {
&::after {
transform: translate(-$unit-1, 50%);
}
}
}
}
2. 带有边角的 Tooltip
另外,有一些提示有边角,例如 A step-by-step guide to making pure-CSS tooltips 一文所展示的那样,在本文中实现了一个最基本的边角提示。
边角使用 ::before
表现,核心样式是:
border-bottom-color
,设置边角的颜色margin-left
,设置边角的大小,为负值就会出现三角形
参考样式代码
.tooltip {
&::before {
border: $corner-size solid transparent;
border-bottom-color: rgba($dark-color, .95);
bottom: 100%;
content: '';
display: block;
height: 0;
width: 0;
opacity: 0;
left: 50%;
margin-left: -$corner-size;
position: absolute;
transform: translate(-50%, $unit-2);
transition: opacity .2s, transform .2s;
z-index: 200;
}
&.tooltip-left {
&::before {
bottom: 50%;
left: auto;
right: 100%;
transform: translate(1rem, 50%) rotate(90deg);
}
&::after {
bottom: 50%;
left: auto;
right: 100%;
transform: translate($unit-2, 50%);
}
&:focus,
&:hover {
&::before {
transform: translate($corner-size, 50%) rotate(90deg);
}
&::after {
transform: translate(-$unit-1, 50%);
}
}
}
}