iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
自我挑戰組

冒險村-30 Day Ruby on Rails Tips Challenge系列 第 15

冒險村15 - customize tooltips with data attribute

15 - customize tooltips with data attribute

雖然這次想介紹的東西偏向後端為主,不過畢竟寫 ROR 除非前後端完全分離,不然多少還是會碰到前端一些,想到 tooltips 基本上是每個網站多多少少會有的功能,但如果是用 bootstrap 或者其他的套件可能就會踩到 Turbolinks 的雷,又或者是還要載入 Enable tooltips everywhere,所以與其用別人寫好的還要套來套去,不如直接手刻一個讓整個網站都能使用吧!

data-* attribute

data-全域屬性構成一組稱作自訂 data 屬性的屬性。它能令 HTML 與其 DOM 擁有給腳本用的交換資訊。這種屬性設置的自訂資料,能透過元素的 HTMLElement 介面而活用。HTMLElement.dataset property 允許訪問它們。 可以是任何遵循以下規則的 xml 名稱(取自 MDN data-*):

  • 名字絕對不能以 xml 起頭,無論是否用於 xml、
  • 名字絕對不能包含分號(U+003A)、
  • 名字絕對不能包含大寫 A 到大小 Z 的拉丁字母。

簡單來說 * 後的字串可自定義名稱,例如: data-item="1"data-content="chester_tang"

  <table>
    <!-- thead -->

    <tbody>
      <% @users.each do |user| %>
        <tr>
          <td><%= user.name %></td>
          <td><%= user.email %></td>
          <td data-explain-tooltip="<%= user.country.alpha_2_code %>"><%= user.tel %></td>
          <td><%= link_to 'Show', user %></td>
          <td><%= link_to 'Edit', edit_user_path(user) %></td>
          <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        </tr>
      <% end %>
    </tbody>
  </table>

Settings app > assets > stylesheets > explain_tooltip.scss

設定 ::after 偽元素來將自訂的資料傳入 scss 內顯示在 content 中,並在 hover 到加入延遲、visible,其餘就只是單純的簡易 style 設定,是不是簡單又方便啊...

  [data-explain-tooltip] {
    position: relative;
  }

  [data-explain-tooltip]::after {
    content: attr(data-explain-tooltip);
    font-size: 10px;
    color: #777;
    white-space: nowrap;

    position: absolute;
    left: 0;
    visibility: hidden;
    z-index: 10;
    bottom: 100%;

    border-width: 1px;
    border-color: #fa0;
    border-radius: 0.25rem;
    background-color: red;
    padding: .25rem .5rem;
  }

  [data-explain-tooltip]:hover::after {
    visibility: visible;
    transition-delay: 300ms;
  }

參考來源

My blog


上一篇
冒險村14 - counter cache
下一篇
冒險村16 - customize breadcurmb
系列文
冒險村-30 Day Ruby on Rails Tips Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言