Skip to content

如何实现一个tooltip组件

  1. 首先编写HTML代码如下
html
<section class="tooltip-box">
    <button class="btn" tooltip="提示消息">按钮</button>
</section>
<section class="tooltip-box">
    <button class="btn" tooltip="提示消息">按钮</button>
</section>
  1. 编写样式文件
scss
.tooltip-box {
  .btn {
    width: 200px;
    height: 60px;
    background-color: pink;
    border-radius: 30px;
    position: relative;
    transition: all 0.3s;

    &::after {
      content: attr(tooltip);
      background: #333;
      color: white;
      position: absolute;
      top: 0;
      width: 200px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      left: 50%;
      transform: translate(-50%, calc(-100% - 10px));
      border-radius: 20px;
    }

    &::before {
      content: "";
      background-color: #333;
      position: absolute;
      width: 15px;
      height: 15px;
      top: 0;
      left: 50%;
      transform: translate(-50%, calc(-100% - 5px)) rotate(45deg);
    }

    &::after,
    &::before {
      display: none;
    }

    &:hover::after,
    &:hover::before {
      display: block;
    }
  }
}
.tooltip-box {
  .btn {
    width: 200px;
    height: 60px;
    background-color: pink;
    border-radius: 30px;
    position: relative;
    transition: all 0.3s;

    &::after {
      content: attr(tooltip);
      background: #333;
      color: white;
      position: absolute;
      top: 0;
      width: 200px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      left: 50%;
      transform: translate(-50%, calc(-100% - 10px));
      border-radius: 20px;
    }

    &::before {
      content: "";
      background-color: #333;
      position: absolute;
      width: 15px;
      height: 15px;
      top: 0;
      left: 50%;
      transform: translate(-50%, calc(-100% - 5px)) rotate(45deg);
    }

    &::after,
    &::before {
      display: none;
    }

    &:hover::after,
    &:hover::before {
      display: block;
    }
  }
}

最终的效果如下