纯 css 打造一个小提示 tooltip

最后编辑:2020/03/24

无意间在寻找资料时候,发现一个不错的小提示,查看源码竟然是纯手工 css 编写(文章底部参考链接)。

效果

小提示效果图

使用的特性

  • css2 中的 attr 函数,所以现在(2019/11/26)主流浏览器基本都兼容

  • 为了更加精准定位使用了 css3 中的 calc 函数,如果被要求的浏览器不支持,那么降级处理的最好方式就是手动计算定位

Code

<element data-title="回到顶部"></element>
// 背景色
$tooltip-fill-color:     rgba(#000, .8) !default;
// 垂直方向的内边距
$tooltip-y-padding:      3px !default;
// 水平方向的内边距(采用 1:2 方式拉伸)
$tooltip-x-padding:      2 * $tooltip-y-padding !default;
// 小箭头的宽度
$tooltip-arrow-width:    5px !default;
// 字体的准线高度(为了垂直居中)
$tooltip-line-height:    1.5 !default;

// 指定的包含 data-title 的元素
*[data-title] {
  overflow: hidden;

  &:before,
  &:after {
    position: absolute;
    z-index: 10;
    opacity: 0;
    // 小偏移可去除(采用了 css3,低版本浏览器可移除)
    transform: translate3d(-50%, 0, 0);
    transition: 300ms ease;
  }

  &:before {
    // 获取 data-title 的值
    content: attr(data-title);
    // 开始计算上浮偏移量,相加之后采用负数向上偏移)
    // 首先是字体的高度 1em * $tooltip-line-height
    // 然后是垂直方向上的内边距,注意分上下,所以是 $tooltip-y-padding * 2
    // 最后是小箭头的宽度(其实也是高度)
    top: calc(#{-1em * $tooltip-line-height} - #{$tooltip-y-padding * 2} - #{$tooltip-arrow-width});
    left: 50%;
    padding: $tooltip-y-padding $tooltip-x-padding;
    line-height: $tooltip-line-height;
    border-radius: 4px;
    background-color: $tooltip-fill-color;
    color: #fff;
    // 字体不给换行,字多的提示可能需要换个表现方式
    white-space: nowrap;
    // 重点:我们使用内容填充,因为我们不知道字体大小
    box-sizing: content-box;
  }
  
  // 小箭头
  &:after {
    content: "\20";
    top: -1 * $tooltip-arrow-width;
    left: 50%;
    border: $tooltip-arrow-width solid transparent;
    border-top-color: $tooltip-fill-color;
  }

  &:hover {
    overflow: visible;

    &:before,
    &:after {
      opacity: 1;
      // 偏移,低版本可移除
      transform: translate3d(-50%, -3px, 0);
    }
  }
}

最终编译出来结果:

*[data-title] {
  overflow: hidden;
}
*[data-title]:before, *[data-title]:after {
  position: absolute;
  z-index: 10;
  opacity: 0;
  transform: translate3d(-50%, 0, 0);
  transition: 300ms ease;
}
*[data-title]:before {
  content: attr(data-title);
  top: calc(-1.5em - 6px - 5px);
  left: 50%;
  padding: 3px 6px;
  line-height: 1.5;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff;
  white-space: nowrap;
  box-sizing: content-box;
}
*[data-title]:after {
  content: "\20";
  top: -5px;
  left: 50%;
  border: 5px solid transparent;
  border-top-color: rgba(0, 0, 0, 0.8);
}
*[data-title]:hover {
  overflow: visible;
}
*[data-title]:hover:before, *[data-title]:hover:after {
  opacity: 1;
  transform: translate3d(-50%, -3px, 0);
}

这就是全部的实现代码,仅仅实现基本功能,如果是要更加健壮,那么还需要考虑更多情况。

比如我考虑的一点就是我仅仅需要在 pc 上展示,所以可以做一个小自适应,即使用下面的代码包裹住:

@media screen and (min-width: 992px) {
  /* 上面的编译后 css 代码 */
}

需求太多,自求多福😂

转载请注明,本文地址:https://www.cnblogs.com/blackcat/p/11933690.html

posted @ 2019-11-26 10:25  神仙梨子丶  阅读(747)  评论(0编辑  收藏  举报