我在用这个css专用的工具提示。如何显示格式化文本并在工具提示文本中添加换行符?
代码:
[data-tooltip-text]:hover {
position: relative;
}
[data-tooltip-text]:hover:after {
background-color: #000000;
background-color: rgba(0, 0, 0, 0.8);
-webkit-box-shadow: 0px 0px 3px 1px rgba(50, 50, 50, 0.4);
-moz-box-shadow: 0px 0px 3px 1px rgba(50, 50, 50, 0.4);
box-shadow: 0px 0px 3px 1px rgba(50, 50, 50, 0.4);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
color: #FFFFFF;
font-size: 12px;
content: attr(data-tooltip-text);
margin-bottom: 10px;
top: 130%;
left: 0;
padding: 7px 12px;
position: absolute;
width: auto;
min-width: 50px;
max-width: 300px;
word-wrap: break-word;
z-index: 9999;
}<span data-tooltip-text="My Heart leaps up when I behold A rainbow in the sky: So was it when my <b>life</b> began; <br/> So be it now I am a man So be it when I shall grow old, Or let me die! The Child is father of the Man; And I could wish my days to be Bound each to by natural piety.">THIS IS LONG TOOLTIP</span>
发布于 2021-12-17 09:05:08
你得做两件事。
第一个是将white-space: pre;添加到伪元素中。这种方式--如果你使用换行器--它们会被打印为换行符。通常,HTML只为<br>打印换行符,但是添加它也会中断字符串中的实际换行。
[data-tooltip-text]:hover:after {
...
white-space: pre;
}其次,CSS中的换行符是用\a而不是\r或\n来表示的,要使它在元素属性中工作,您需要像
一样转义它。
<span data-tooltip-text="A
tooltip
with
linebreaks">THIS IS LONG TOOLTIP</span>发布于 2021-12-17 09:17:17
不幸的是,这是不可能的。content:不解释字符串,因此它不会生成HTML、<br/>, <b>等,但是您可以帮助它处理JavaScript。或者你可以稍微改变一下你的结构。不使用数据属性,而是将文本的内容放入子元素中。这样,工具提示中的HTML就不会有任何问题。
工作示例
.tooltip {
position: relative;
display: inline-block;
cursor: pointer;
}
.tooltip .tooltiptext {
background-color: #000000;
background-color: rgba(0, 0, 0, 0.8);
-webkit-box-shadow: 0px 0px 3px 1px rgba(50, 50, 50, 0.4);
-moz-box-shadow: 0px 0px 3px 1px rgba(50, 50, 50, 0.4);
box-shadow: 0px 0px 3px 1px rgba(50, 50, 50, 0.4);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
color: #FFFFFF;
font-size: 12px;
margin-bottom: 10px;
top: 130%;
left: 0;
padding: 7px 12px;
position: absolute;
width: auto;
min-width: 50px;
max-width: 300px;
word-wrap: break-word;
z-index: 9999;
visibility: hidden;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}<div class="tooltip">THIS IS LONG TOOLTIP
<span class="tooltiptext">My Heart leaps up when I behold A rainbow in the sky: So was it when my <b>life</b> began; <br/> So be it now I am a man So be it when I shall grow old, Or let me die! The Child is father of the Man; And I could wish my days to be Bound each to by natural piety.</span>
</div>
https://stackoverflow.com/questions/70390604
复制相似问题