CSS 内容 class 而不是 attr

CSS content class rather than attr

我想将现有标记传递给使用 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:博士;我想使用 class 从现有标记中提取内容,而不是使用 title 属性。

使用纯 CSS(或什至使用预处理器)没有真正的方法来选择元素的整个文本内容并将其分配给 content 属性。 content 属性只能有预定义的字符串、URL、属性值或计数器作为值。

您可以使用 jQuery(或普通 JS)自动将 toolTip class 和 title 属性添加到具有所需 class (.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>