Hover-Tip 實現

經常使用於展現鼠標 hover 時的提示信息。css

該組件的痛點在於:
  • 純CSS實現;
  • 如何利用slot使組件易擴展,可以適應多種場景。

1. 實例

最終效果

代碼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

2. 原理

因爲須要Hover-tip組件具有良好的擴展性較好,因此採用具名插槽來完成。github

將該組件分爲兩個部分:bash

  • hover-part:鼠標hover區域;
  • tip-part:展現提示框的內容,具體以下圖。
最終效果

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-partspa

.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%
複製代碼

leftbottom偏移的單位分別爲包含塊的寬和高,以後tip-part還須要向左偏移本身的50%,因此添加transform: translateX(-50%);,此時tip-part位於hover-tip上方的正中間,如示意圖。

最終效果

一樣能夠開發bottom-centerleft-centerright-center。因爲bottom-centertop-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%;
}
複製代碼

3. 使用

使用時,主要注意點是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>
複製代碼

原創聲明: 該文章爲原創文章,轉載請註明出處。

相關文章
相關標籤/搜索