笔记:伪类中结合 content 和 attr() 获取元素的 dataset


基础:

在伪类 :before:after 中的使用 content 属性来为 HTML 局部添加内容现在已经成了很常见的做法,特别是一些 icon 的显示,非常好用,最基本的使用如下:

<style>
div:after {
  content: "text from 'content' property";
}
</style>

<div></div>

但今天看到一篇文章 知道了其实 content 属性中其实还可以直接获取元素的 attribute 属性:

div:after {
  content: attr(text);
}
</style>

<div text="text from 'text' attribute"></div>

demo:

See the Pen dataset in CSS by Lien (@movii) on CodePen.

标题中获取 dataset,这里首先得明确一下,其实直接获取元素的 attribute 也是可以的。而为什么尽量使用 dataset 下文中会提到。

在上面例子中直接使用的 text="text from 'text' attribute",原文中不太推荐这么做,因为这是一个 attribute:

attr is typically used with custom data- attributes since traditional element attributes are good for functionality but not so much or text presentation.

不做直接翻译,大概理解为:HTML 标签里的 attribute 是功能性的,比如 <select> 里的 required 或者 <option> 上可以加入的 selected,虽然可以使用,但不推荐,因为在这里只是一段 text 数据,属于 data 的范畴,按照语义化更应该使用 data-text 在这里写入数据。所以上面的例子可以写成这样:

div:after {
  content: attr(data-text);
}
</style>

<div data-text="text from 'text' attribute"></div>

另一个结合 :after:hover 的例子:

See the Pen dataset in CSS 2 by Lien (@movii) on CodePen.


concatenate attr() with text:

还有另外一种用法也是上文中提到的 blog 文章中介绍的,将获取到的 data-text 与别的内容合并:

<style>
div:after {
  content: "content + " attr(data-text);
}
</style>

<div data-text="text from 'text' attribute"></div>

See the Pen dataset in CSS 2 by Lien (@movii) on CodePen.

感谢阅读

你们好, 2018 年初把小站从 Jekyll 迁移到 Hugo 的过程中,删除了评论区放的 Disqus 插件,考虑有二:首先无论评论、还是对笔记内容的进一步讨论,读者们更喜欢通过邮件、或者 Twitter 私信的方式来沟通;其次一年多以来 Disqus 后台能看到几乎都是垃圾留言(spam),所以这里直接贴一下邮件、以及 Twitter 账户 地址。

技术发展迭代很快,所以这些笔记内容也有类似新闻的时效性,不免有过时、或者错误的地方,欢迎指正 ^_^。

BEST
Lien(A.K.A 胡椒)
本站总访问量 本站总访客量 本文总阅读量