该组件的痛点在于:经常使用于展现鼠标 hover 时的提示信息。css
slot
使组件易扩展,可以适应多种场景。代码html
<!-- 基础用法 -->
<fat-hovertip>
<template slot="hover-part">
<fat-button>组件</fat-button>
</template>
<template slot="tip-part">向下</template>
</fat-hovertip>
复制代码
实例地址:Hover-Tip 实例vue
代码地址:Github UI-Librarygit
因为须要Hover-tip组件具有良好的扩展性较好,因此采用具名插槽来完成。github
将该组件分为两个部分:bash
template
的基本结构为ide
<div :class="['hover-tip', customClass]">
<div class="hover-part"> <slot name="hover-part"> <!-- slot 的默认节点 --> <fat-icon name="help" size="18" /> </slot> </div> <div :class="[type, 'tip-part']"> <slot name="tip-part"></slot> <div class="arrow"></div> <div class="block"></div> </div> </div>
复制代码
template
中具备两个具名插槽,其中<slot name="hover-part">
为鼠标hover区域,能够为它设定默认值,以减小项目中代码的冗余。 <slot name="tip-part>
表明提示框的内容区域,彻底自定义。flex
相关样式:tip-part的显示、tip-part的相对位置。ui
鼠标hover
的时候,显示tip-part
spa
.hover-tip {
position: relative;
display: inline-flex;
.hover-part {
display: flex;
align-items: center;
}
// 初始的tip-part的display为none
.tip-part {
display: none;
...
}
// 当鼠标hover的时候hover-part区域的时候,显示tip-part
.hover-part:hover + .tip-part {
display: block;
}
}
复制代码
tip-part
的位置,以及上方居中为例top-center
$base-offset: 8px;
.top-center {
margin-bottom: $base-offset;
position: absolute;
left: 50%;
bottom: 100%;
transform: translateX(-50%);
}
复制代码
tip-part
为绝对定位,其最近的非 static 定位祖先元素为hover-tip
,相对于它偏移
/* <percentage>s of the width of the containing block */
left:50%;
/* <percentage>s of the height of the containing block */
bottom:100%
复制代码
left
,bottom
偏移的单位分别为包含块的宽和高,以后tip-part
还须要向左偏移本身的50%,因此添加transform: translateX(-50%);
,此时tip-part位于hover-tip
上方的正中间,如示意图。
一样能够开发bottom-center
,left-center
,right-center
。因为bottom-center
,top-center
有公共部分,可进一步聚合
.top-center,
.bottom-center {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
.bottom-center {
margin-top: $base-offset;
top: 100%;
}
.top-center {
margin-bottom: $base-offset;
bottom: 100%;
}
复制代码
使用时,主要注意点是Hover-tip组件的两个具名插槽的使用。
<fat-hovertip>
<!-- 对应slot name="hover-part" -->
<template slot="hover-part">
<fat-button>组件</fat-button>
</template>
<!-- 对应slot name="tip-part" -->
<template slot="tip-part">向下</template>
</fat-hovertip>
复制代码
原创声明: 该文章为原创文章,转载请注明出处。