-2

我正在写一个演练,我希望读者能够将鼠标悬停在脚本中任何位置的单词上并获得定义,但我只想定义缩写一次。有没有办法在 html 或 css 中做到这一点?

4

1 回答 1

0

实现此目的的一种方法是使用带有伪元素的自定义工具提示。

首先,在您的 HTML 中,您将要定义的单词包含在 a span(或者可能是 an<a>或其他)中:

<p>This is a word I want to <span class="tooltip">define</span>.</p>

然后,您可以为工具提示提供第二个类,您可以使用它来设置它们的内容。这样,您可以在 HTML 中包含您想要定义的所有单词,但可以从一个中心位置(您的样式表)控制它们的内容,并且如果定义需要调整,则不必修改 HTML。

<p>This is a word I want to <span class="tooltip define">define</span>.</p>

在您的样式表中,您将设置与 一起使用的伪元素的基本样式.tooltip,然后执行以下操作以使用第二个类设置特定内容:

.tooltip.define::before {
  content: 'determine or identify the essential qualities or meaning of';
}

其中最棘手的部分实际上是将工具提示的样式设置为您喜欢的样式。

在下面的示例中,我white-space: nowrap在伪元素上设置了一个最小宽度来代替。否则,您会发现文本以非常小的宽度换行。这适用于所有相对较短的定义,但如果您有一些需要大量文本的定义和其他需要一个或两个单词定义的定义,您可能还需要width在样式中包含伪元素的与您的第二类(用于指定content)一起使用,以避免出现这样的情况:您有巨大的容器来容纳微小的内容或大量的自动换行来进行长定义。

例如:

.tooltip.longtext {
  content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam interdum magna sit amet magna condimentum, id gravida tellus luctus. Nullam posuere eget lacus sit amet pulvinar.';
  min-width: 300px;
}
.tooltip.shorttext {
  content: 'Lorem ipsum';
  min-width: 0;
}

span {
  position: relative;
  color: blue;
}
.tooltip::before {
  display: block;
  position: absolute;
  z-index: -1;
  top: -100%;
  left: -50%;
  padding: 2px 5px;
  white-space: nowrap;
  font-size: 12px;
  text-align: center;
  background: #565656;
  color: white;
  visibility: hidden;
}
.tooltip:hover {
  cursor: pointer;
}
.tooltip:hover::before {
  visibility: visible;
  z-index: 1;
}
.tooltip.lots::before {
  content: 'many, several';
}
.tooltip.words::before {
  content: 'things that are said';
}
.tooltip.going::before {
  content: 'taking a certain course';
}
<p style="margin-top: 30px;">This is a very long paragraph that has <span class="tooltip lots">lots</span> and <span class="tooltip lots">lots</span> of <span class="tooltip words">words</span> you want to define, and it just keeps <span class="tooltip going">going</span> and <span class="tooltip going">going</span>, and some of the <span class="tooltip words">words</span> are the same, and you don't want to have to define them more than once.</p>

于 2017-06-08T23:05:15.893 回答