我想将现有标记传递给使用 css 构建的工具提示,目前使用 attr(title) 但必须复制标记以获得所需结果。
考虑:
<p class="toolTip" title="this is a tooltip">hover over me</p>
<p class="existing">this is a tool tip</p>
.toolTip:hover:after{
content: attr(title);
}
我希望能够做的是这样的事情:
.toolTip:hover:after{
content: class(existing); //invalid I know!
}
tl: 博士;我想使用类而不是使用 title 属性从现有标记中提取内容。
最佳答案
使用纯 CSS(或什至使用预处理器)没有真正的方法来选择元素的整个文本内容并将其分配给 content
属性。 content
属性只能有预定义的字符串、URL、属性值或计数器作为值。
您可以使用 jQuery(或纯 vanilla JS)自动将 toolTip
类和 title
属性添加到所有具有所需类(. existing
) 并将元素的文本内容分配给该属性。这样您就不必复制 CSS 规则。
Note: This is just a simple example on how to set the content of an element to its title attribute but in real world scenario you would need more because there is not much point in setting the actual content itself as tooltip.
$(document).ready(function() {
$('.existing').addClass('toolTip');
$('.existing').each(function() {
$(this).attr('title', $(this).text());
});
});
.toolTip:hover:after {
content: attr(title);
/* just for demo */
position: relative;
left: 10px;
border: 1px solid green;
background: lightgreen;
padding: 2px;
border-radius: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="toolTip" title="this is a tooltip">hover over me</p>
<p class="existing">this is a tool tip</p>
一个不同的示例:这是一个略有不同的示例,其中工具提示与元素的内容不同。这里元素的内容是父元素的内容,工具提示文本最初出现在子元素中(使用 class="existing"
)。使用 jQuery 将此子级 span
的内容添加到父级的 title
属性。
$(document).ready(function() {
$('.existing').parent().addClass('toolTip');
$('.existing').each(function() {
$(this).parent().attr('title', $(this).text());
});
});
.toolTip:hover:after {
content: attr(title);
/* just for demo */
position: relative;
left: 10px;
border: 1px solid green;
background: lightgreen;
padding: 2px;
border-radius: 2px;
}
.existing {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="toolTip" title="this is a tooltip">hover over me</p>
<p>hover over me <span class="existing">this is a tool tip</span>
</p>
<div>I have a tooltip too<span class="existing">See, I told you!</span>
</div>
关于jquery - CSS 内容类而不是 attr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28297798/