无心间在寻找资料时候,发现一个不错的小提示,查询了下源码,居然是纯手工 css
编写,文章底部参考连接。css
css2
中的 attr
函数,因此如今(2019/11/26)主流浏览器基本都兼容css3
为了更加精准定位使用了 css3
中的 calc
函数,若是被要求的浏览器不支持,那么降级处理的最好方式就是手动计算定位浏览器
// 背景色 $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 cubic-bezier(0.215, 0.61, 0.355, 1); } *[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(73, 80, 87, 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(73, 80, 87, 0.8); } *[data-title]:hover { overflow: visible; } *[data-title]:hover:before, *[data-title]:hover:after { opacity: 1; transform: translate3d(-50%, -3px, 0); }
这就是所有的实现代码,仅仅实现基本功能,若是是要更加健壮,那么还须要考虑更多状况。字体
好比我考虑的一点就是我仅仅须要在 pc
上展现,因此能够作一个小自适应,即便用下面的代码包裹住:spa
@media screen and (min-width: 992px) { /* 上面的编译后 css 代码 */ }
需求太多,自求多福😂3d