纯css实现(无脚本)Html指令式tooltip文字提示效果

2020-04-17 08:19:50易采站长站整理

border: 1px solid $black;
}

/* 三角形主题 */
.triangle-theme-dark {
border-top-color: $black;
}

.triangle-theme-light {
border-top-color: $black; /* 暂时跟dark一样 */
}

定制气泡、三角形位置(只示例一个方向)


/* 气泡位置 */

/*----上----*/
.tooltip-placement-top {
bottom: calc(100% + 10px);
left: 50%;
transform: translate(-50%, 0);
}

.tooltip-placement-top-right {
bottom: calc(100% + 10px);
left: 100%;
transform: translate(-100%, 0)
}

.tooltip-placement-top-left {
bottom: calc(100% + 10px);
left: 0;
transform: translate(0, 0)
}

/* 三角形位置 */

/*----上----*/
.triangle-placement-top {
bottom: calc(100% + 5px);
left: 50%;
transform: translate(-50%, 0);
}

.triangle-placement-top-left {
bottom: calc(100% + 5px);
left: 10px;
}

.triangle-placement-top-right {
bottom: calc(100% + 5px);
right: 10px;
}

捕捉位置、主题

这里也算最核心的代码了,用属性选择器来匹配标签上的值,然后设置不同的样式

匹配气泡、三角形主题


&[effect="light"] {
&::after {
@extend .tooltip-theme-light;
}

&::before {
@extend .triangle-theme-light;
}
}

匹配气泡、三角形位置,12种位置


@each $placement in top,top-right,top-left,
right,right-top,right-bottom,
bottom,bottom-right,bottom-left,
left,left-top,left-bottom {
&[placement="#{$placement}"] {
&::after {
@extend .tooltip-placement-#{$placement};
}

&::before {
@extend .triangle-placement-#{$placement};
}
}
}

标签不存在placement 属性 / 为空的时候,默认继承top位置


&:not([placement]),
&[placement=""] {
&::after {
@extend .tooltip-placement-top;
}

&::before {
@extend .triangle-placement-top;
}
}

目前效果如下

让我们把文字放长,把气泡、三角形的默认样式加上display:none看看

 加个动画

分四个方向,上下左右,四个动画


@keyframes anime-top {
from {
opacity: .5;
bottom: 150%;
}
}

@keyframes anime-bottom {
from {
opacity: .5;
top: 150%;
}
}

@keyframes anime-left {
from {
opacity: .5;
right: 150%;
}
}

@keyframes anime-right {