页面设计的时候,有时候,我们需要在一段文字或者按钮添加一个提示组件,原先一般通过模态组件模拟一个,但是现在我们可以只通过样式就可以做到,同时为了支持扩展,我们使用scss来书写。

首先,我们需要一个箭头,支持四个方向,大小,以及颜色的扩展:

@charset "utf-8";
// 生成三角形
@mixin arrow ($direction: top, $color: black, $size: 12px) {
    $dire: (top: "bottom", bottom: "top", left: "right", right: "left");
    display: inline-block;
    width: 0;
    height: 0;
    line-height: 0;
    font-size: 0;
    overflow: hidden;
    border-style: solid;
    border-width: $size;
    // 三角形的角度计算
    border-#{map-get($dire, $direction)}-width: $size * 0.64;
    border-color: transparent;
    cursor: pointer;
    border-#{map-get($dire, $direction)}-color: $color;
    border-#{$direction}: none;
    

然后我用用::before元素构造一个三角形,用::after元素构造tootip内容,通过content和attr()展现内容:

@charset "utf-8";
@import './arrow';
@mixin tooltip($pos: top, $bgcolor: #2d8cf0) {
  $dire: (top: 'bottom', bottom: 'top', left: 'right', right: 'left');
  @if not map-get($dire, $pos) {
    @error "illegalArgumentException";
    position: relative;
  &:hover{
    &::before,&::after{
      visibility: visible;
      opacity: 1;
  &::before{
    position: absolute;
    #{$pos}: 0px;
    @if $pos == 'top' or $pos == 'bottom' {
      left: 50%;
      transform: translateX(-50%);
      margin-#{$pos}: -8px;
    } @else if $pos == 'left' or $pos == 'right' {
      top: 50%;
      transform: translateY(-50%);
      margin-#{$pos}: -14px;
    content: "";
    @include arrow(#{map-get($dire, $pos)}, $bgcolor);
    visibility: hidden;
    opacity: 0;
    transition: opacity 1s;
  &::after{
    position: absolute;
    @if $pos == 'top' or $pos == 'bottom' {
      $y: if($pos == 'top', calc(-100% - 4px), calc(100% + 4px));
      #{$pos}: 0px;
      left: 50%;
      transform: translateX(-50%) translateY($y);
    } @else if $pos == 'left' or $pos == 'right' {
      #{map-get($dire, $pos)}: 0px;
      top: 50%;
      transform: translateY(-50%);
      margin-#{map-get($dire, $pos)}: calc(100% + 8px);
    max-width: 200px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    content: attr(data-tiptext);
    color: #fff;
    font-size: 12px;
    line-height: 2;
    padding: 0.2em 2em;
    border-radius: 2em;
    background: $bgcolor;
    visibility: hidden;
    opacity: 0;
    transition: opacity 1s;
    

样式使用:

<style lang="scss">
@import './tooltip';
.tooltip{
    @include tooltip(bottom); // 默认是top
</style>
    

效果展示:

传送门: github.com/luyuchen627…