主页

ruby on rails 页面增加tooltips

2025-09-12 05:47PM

方法1:使用原生的  html title 属性

最简单的方法就是使用 HTML 原生的 title 属性,rails的很多视图辅助方法(如:link_to、button_to、甚至是 form 元素相关的辅助方法)都支持直接传入 HTML 选项,其中就包含 title

<%= button_to "全选", submit_form_path, title: "选择所有可用的社交平台" %>

优点:实现速度非常快,无需任何额外的配置或样式,浏览器默认支持

缺点:样式很简陋,并且触发方式很单一(只能悬停),提示框也会出现一定的延迟

方法2:使用CDN

1. 在 app/views/layouts/application.html.erb  中添加 CDN 的链接


<head>
  <!-- 添加这行 -->
  <script src="https://unpkg.com/@popperjs/core@2"></script>
  <script src="https://unpkg.com/tippy.js@6"></script>
</head>  

2. 在 app/assets/stylesheets/application.css 文件中添加下面的内容

  <style>
    /* 可选:基础样式 */
    .tippy-box {
      background: #333;
      color: white;
      border-radius: 8px;
      padding: 8px 12px;
      font-size: 14px;
      opacity: 0.9;
    }
  </style>

3. 在任意地方使用

 <button class="btn btn-sm btn-outline-primary me-2" data-tippy-content="选择所有可用的社交平台">全选</button>

<script>
  // 自动初始化所有有 data-tippy-content 的元素
  tippy('[data-tippy-content]');
</script>

 

方法3:使用超轻的 CSS-Only 方法(无需JS)

这是一个「一站式」CSS 方案,复制粘贴就能用,样式也很好看:

/* 添加到你的 application.css */
.tooltip {
  position: relative;
  display: inline-block;
  cursor: pointer;
  border-bottom: 1px dotted #666;
}

.tooltip .tooltip-text {
  visibility: hidden;
  width: 200px;
  background-color: #333;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 12px;
  position: absolute;
  z-index: 1000;
  bottom: 125%;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.tooltip .tooltip-text::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #333 transparent transparent transparent;
}

.tooltip:hover .tooltip-text {
  visibility: visible;
  opacity: 1;
}

在任意的 ERB 文件中使用

<span class="tooltip">
  悬停看我
  <span class="tooltip-text">这是一个漂亮的CSS提示框!</span>
</span>

<%= link_to "删除", "#", class: "tooltip" do %>
  删除项目
  <span class="tooltip-text">删除后无法恢复,请谨慎操作!</span>
<% end %>

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论