Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

html - Using attr(data-icon) property to display unicode before element

Lets demonstrate an example with simple HTML code like this:

<div data-icon="25B6">Title</div>

I would like this element to have an prefix icon set by it's data attribute (data-icon) so I set CSS file like this:

div:before {
    content: attr(data-icon);
}

My desired output of this example would look like this:

?Title

Instead of desired output all I can get is this:

25B6Title

So my question is: what am I doing wrong / what am I missing?

JSFiddle example: http://jsfiddle.net/Lqgr9zv6/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CSS escape sequences only work within CSS strings. When you take a CSS escape sequence from an HTML attribute (i.e. outside of CSS), it will be read literally, not interpreted as part of a CSS string.

If you want to encode the character within an HTML attribute, you need to encode it as an HTML entity. This will be seen by CSS as the corresponding Unicode character. Since this is a hexadecimal escape sequence you can transliterate it like so:

<div data-icon="&#x25B6;">Title</div>

Alternatively you can just use the Unicode character itself:

<div data-icon="?">Title</div>

If the attribute's value needs to be reactive in Vue or any of the now popular JavaScript frameworks, use the JavaScript escape sequence notation, within a JavaScript string (if you're confused, just pay attention to the nested quotes in the following example):

<div :data-icon="'u25b6'">Title</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...