CSS:在内容中编码字符后

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5030551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:44:25  来源:igfitidea点击:

CSS:after encoding characters in content

cssunicodecss-selectorspseudo-elementcss-content

提问by theorise

I am using the following CSS, which seems to be working:

我正在使用以下 CSS,它似乎有效:

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

The characters however cannot seem to be encoded like this, as the output is literal and shows the actual string:

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

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

If I can't encode it, it feels like I should use something such as .append() in jQuery, as that supports the encoding. Any ideas?

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

回答by BoltClock

To use encoded Unicode characters in contentyou need to provide either the characters themselves (as you do), or their UTF-8 escape sequences instead of HTML entities:

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

a.up:after { content: " 93"; }
a.down:after { content: " 91"; }   

回答by Felix

Why do you want to encode those characters anyway? Remember, you're writing CSS, not HTML. Your code:

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

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

is perfectly valid, as long as you save the file with UTF-8 encoding and send the appropriate header:

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

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

Encoding characters is only used in HTML so that there is no ambiguity between content and tags. Thus, you would encode<as &lt;so that the browser doesn't think it's the beginning of a tag. Stuff like &darr;are just commodities for people who don't know how to use utf-8 (or can't, for whatever reason) :).

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

回答by keepAlive

Just want to add that if you want to set dynamicallythe value of contentvia the attr() function, the above won't work. See

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

document.getElementById('wontwork').setAttribute('data-sym', ' 14 ');
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>