jquery - CSS 内容类而不是 attr

标签 jquery css class 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: 博士;我想使用类而不是使用 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/

相关文章:

php - Symfony 2 KNP 菜单 : add CSS class to link

c++ - 类函数的多定义错误

c++ - 类函数上的新线程

javascript - 使用变量一次

javascript - 如何使用 Alpine.js 创建动画数字计数器?

html - 更改悬停链接上 Bootstrap 导航栏的颜色?

class - uml类图关联

javascript - jquery自动按钮点击问题

javascript - 在span标签上使用on函数

javascript - 如何使用 jQuery 创建带有嵌套子菜单的下拉菜单