高效 HTML 工具提示渲染(重用工具提示)

Efficient HTML tooltip rendering (reusing tooltips)

我正在生成 html 在字段级别显示记录(即名称、出生日期、最喜欢的编程语言等),并正在为每个字段创建 html 工具提示。

我知道 headers 可以使用,但我正在显示不同类型的记录,并希望允许用户快速工具提示以显示他们正在查看的内容。

这适用于少量记录,但当我有数千条记录时,html 主要由相同的工具提示数据一遍又一遍地组成。

我想以某种方式 pre-create css 或 javascript 中的这些工具提示只需要在页面上呈现一次实际的工具提示内容,但可以通过指定 class(或类似的)。

例如,给定:

<div class="field tooltip">bar<span class="tooltiptext">This
 field represents what foo needs</span></div>

我想改用这样的东西:

<div class="field tooltip tt-bar">bar</div>

其中 tt-bar 指的是使用 css and/or javascript.

创建的工具提示

如有任何想法,我们将不胜感激。

注意:我没有使用 JQuery 或任何其他库,我想保持这种状态。

这是一个仅使用 CSS 的相当快速但肮脏的解决方案。

*[data-tooltip] {
  text-decoration: underline dashed;
  position: relative;
}

*[data-tooltip]:hover:before {
  background: #333;
  border-radius: 4px;
  color: #ccc;
  content: attr(data-tooltip);
  padding: 2px 4px;
  position: absolute;
  white-space: nowrap;
  top: calc(100% + 4px);
}

*[data-tooltip]:hover:after {
  background: #333;
  content: '';
  width: 6px;
  height: 6px;
  position: absolute;
  white-space: nowrap;
  top: calc(100% + 1px);
  left: 8px;
  transform: rotate(45deg);
}
foo <span data-tooltip="This field represents what foo needs">bar</span> baz

如果你的工具提示文本是已知的,你甚至可以摆脱 data-tooltip 属性,并将其烘焙到 CSS 中的 content 属性:

.tooltip {
  text-decoration: underline dashed;
  position: relative;
}

.tooltip:hover:before {
  background: #333;
  border-radius: 4px;
  color: #ccc;
  padding: 2px 4px;
  position: absolute;
  white-space: nowrap;
  top: calc(100% + 4px);
}

.tooltip:hover:after {
  background: #333;
  content: '';
  width: 6px;
  height: 6px;
  position: absolute;
  white-space: nowrap;
  top: calc(100% + 1px);
  left: 8px;
  transform: rotate(45deg);
}

.tooltip.tt-bar:hover:before {
  content: 'This field represents what foo needs';
}
foo <span class="field tooltip tt-bar">bar</span> baz