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

懵懂的女人 提交于 2019-12-30 05:57:08

问题


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/


回答1:


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>

[Minor addition]

Use the Unicode notation if the attribute's value needs to be reactive in Vue or any of the now popular JavaScript frameworks.

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



回答2:


you can uss css triangle for arrow. http://jsfiddle.net/Lqgr9zv6/3/

div{
position:relative;
text-indent:12px;
}


div:before {
content:'';
position:absolute;
left:0;
top:0;
bottom:0;
margin:auto;
width: 0;
height: 0;
border-style: solid;
border-width: 5px 0 5px 10px;
border-color: transparent transparent transparent #000;
}


来源:https://stackoverflow.com/questions/30097807/using-attrdata-icon-property-to-display-unicode-before-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!