添加 CSS
- 为 <a> 标签的 class 属性设置 border-bottom 和 text-decoration 属性。
- 将 :hover 伪类添加到 <a> 标签的 class 属性中。
设置光标和位置属性。
- 将 <a> 标签内的 <span> 元素的显示设置为“无”。
现在我们将添加其余的 CSS 来显示工具提示。
a.tooltip { border-bottom: 1px dashed; text-decoration: none; } a.tooltip:hover { cursor: help; position: relative; } a.tooltip span { display: none; } a.tooltip:hover span { border: #666 2px dotted; padding: 5px 20px 5px 5px; display: block; z-index: 100; background: #e3e3e3; left: 0px; margin: 15px; width: 300px; position: absolute; top: 15px; text-decoration: none; }
让我们看看我们的代码的结果。
在锚标记内设置工具提示样式的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> a.tooltip { border-bottom: 1px dashed; text-decoration: none; } a.tooltip:hover { cursor: help; position: relative; } a.tooltip span { display: none; } a.tooltip:hover span { border: #666 2px dotted; padding: 5px 20px 5px 5px; display: block; z-index: 100; background: #e3e3e3; left: 0px; margin: 15px; width: 300px; position: absolute; top: 15px; text-decoration: none; } </style> </head> <body> <a href="#" class="tooltip">Mouse over the link <span>当鼠标悬停在链接上时显示 CSS 工具提示</span> </a> </body> </html>
正如你在上面的例子中看到的,我们的锚包含一个带有工具提示内容的 <span> 。
也可以使用 CSS 和自定义属性创建伪工具提示。
为此,在我们的下一个示例中,我们使用 data-* 属性,尤其是 data-title 属性。
我们还需要添加 :after(或者 :before)伪元素,它包含使用 attr() 的属性值。
使用 :after 伪元素设置工具提示样式的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> [data-title]:hover:after { opacity: 1; transition: all 0.1s ease 0.5s; visibility: visible; } [data-title]:after { content: attr(data-title); position: absolute; bottom: -1.6em; left: 100%; padding: 4px 4px 4px 8px; color: #666; white-space: nowrap; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; -moz-box-shadow: 0px 0px 4px #666; -webkit-box-shadow: 0px 0px 4px #666; box-shadow: 0px 0px 4px #666; background-image: -moz-linear-gradient(top, #f0eded, #bfbdbd); background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #f0eded), color-stop(1, #bfbdbd)); background-image: -webkit-linear-gradient(top, #f0eded, #bfbdbd); background-image: -moz-linear-gradient(top, #f0eded, #bfbdbd); background-image: -ms-linear-gradient(top, #f0eded, #bfbdbd); background-image: -o-linear-gradient(top, #f0eded, #bfbdbd); opacity: 0; z-index: 99999; visibility: hidden; } [data-title] { position: relative; } </style> </head> <body> <p> <a href="#" data-title="Example"> Link </a> with styled tooltip </p> <p> <a href="#" title="Example"> Link </a> with normal tooltip </p> </body> </html>
创建 HTML
- 使用带有 href 属性的 <a> 标记。
此外,添加一个名为“工具提示”的类属性。
- 在 <a> 标签内放置一个 <span> 元素。
<a href="#" class="tooltip">Link <span>当鼠标悬停在链接上时显示 CSS 工具提示</span> </a>
title 属性的文本如何显示取决于浏览器。
它可能因浏览器而异。
我们无法将我们想要的样式应用于基于 title 属性显示的工具提示。
但是,可以使用其他属性创建类似于它的东西。
在此代码中,我们将演示执行此操作的一些示例。
日期:2020-06-02 22:15:00 来源:oir作者:oir