55

我正在使用以下 CSS,它似乎正在工作:

a.up:after{content: " ↓";}
a.down:after{content: " ↑";}    

然而,字符似乎不能像这样编码,因为输出是文字并显示实际字符串:

a.up:after{content: " ↓";}
a.down:after{content: " ↑";}   

如果我不能对其进行编码,我感觉我应该在 jQuery 中使用诸如 .append() 之类的东西,因为它支持编码。有任何想法吗?

4

3 回答 3

98

要在其中使用编码的 Unicode 字符,content您需要提供字符本身(如您所做的那样),或者它们的 UTF-8 转义序列而不是 HTML 实体:

a.up:after { content: " \2193"; }
a.down:after { content: " \2191"; }   
于 2011-02-17T14:59:24.700 回答
13

你为什么要编码这些字符呢?请记住,您正在编写 CSS,而不是 HTML。你的代码:

a.up:after{content: " ↓";}
a.down:after{content: " ↑";}

完全有效,只要您使用 UTF-8 编码保存文件并发送适当的标头:

Content-Type: text/css; charset=utf-8

编码字符仅在 HTML 中使用,因此内容和标签之间没有歧义。因此,您将编码<&lt;这样浏览器就不会认为它是标签的开头。&darr;对于那些不知道如何使用 utf-8(或不能,无论出于何种原因)的人来说,类似的东西只是商品:)。

于 2011-02-17T15:13:12.600 回答
0

只想补充一点,如果您想动态content设置via的值the attr() function,上述方法将不起作用。看

document.getElementById('wontwork').setAttribute('data-sym', ' \2714 ');
document.getElementById('willwork').setAttribute('data-sym', ' \u2714 ');
button::before {
  content: attr(data-sym);
}
* {
  font-size: 30px
}
<button id='wontwork' data-sym='to-be-replaced'>not rendered</button>
<button id='willwork' data-sym='to-be-replaced'>rendered !</button>

于 2019-09-06T11:20:26.450 回答