點燈坊

失くすものさえない今が強くなるチャンスよ

實作 Tooltip (JavaScript + CSS)

Sam Xiao's Avatar 2024-05-27

Tooltip 為實務上常見效果,可使用 JavaScript + CSS 實現。

Version

CSS 3

Page

tooltip01

Template

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTML Lab</title>
  </head>
  <body>
    <main class="main">
      <div class="hover-me">Hover Me</div>
      <div class="tooltip">This is a tooltip</div>
    </main>
  </body>
  <script>
    let hoverMe = document.querySelector('.hover-me')
    let tooltip = document.querySelector('.tooltip')

    hoverMe.onmouseenter = () => {
      tooltip.style.display = 'block'
    }

    hoverMe.onmouseleave = () => {
      tooltip.style.display = 'none'
    }
  </script>
  <style>
    .main {
      position: relative;

      .hover-me {
        cursor: pointer;
      }

      .tooltip {
        position: absolute;
        top: 25px;
        left: 60px;
        display: none;
        background-color: #333;
        color: #fff;
        padding: 5px;
        border-radius: 5px;
        font-size: 12px;
        white-space: nowrap;
        z-index: 999;
      }
    }
  </style>
</html>

Line 9

<main class="main">
  <div class="hover-me">Hover Me</div>
  <div class="tooltip">This is a tooltip</div>
</main>
  • 分別先由 <div> 實現 text 與 tooltip
  • Tooltip 預設為 隱藏

Line 18

hoverMe.onmouseenter = () => {
  tooltip.style.display = 'block'
}

hoverMe.onmouseleave = () => {
  tooltip.style.display = 'none'
}
  • mouseenter event:當 hover 時顯示 tooltip
  • mouseleave event:當離開時隱藏 tooltip

Line 27

.main {
  position: relative;
}
  • position: relative:外層使用 relative 定位

Line 34

.tooltip {
  position: absolute;
  top: 25px;
  left: 60px;
  display: none;
  background-color: #333;
  color: #fff;
  padding: 5px;
  border-radius: 5px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 999;
}
  • position: absolute:tooltip 使用 absolute 定位
  • display: none:預設不顯示,當 hover 時由 JavaScript 控制顯示
  • white-space: nowrap:只會一行顯示不會換行
  • z-index: 999:將 tooltip 置於最上層

Conclusion

  • 若覺得純粹使用 CSS 實作 tooltip 難度太高,也可搭配 JavaScript 較直覺