使用 JavaScript 和 HTML 打印表情符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22312364/
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-10-27 22:54:19  来源:igfitidea点击:

Printing emojis with JavaScript and HTML

javascripthtmlunicodeemoji

提问by Tom S?derlund

Why does this work:

为什么这样做:

<p id="emoji">&#x1f604;</p>

And this doesn't:

而这不会:

document.getElementById("emoji").innerHTML = String.fromCharCode(parseInt('1f604', 16));

回答by bobince

A 'char' in JS terms is actually a UTF-16 code unit, not a full Unicode character. (This sad state of affairs stems from ancient times when there wasn't a difference*.) To use a character outside of the Basic Multilingual Plane you have to write it in the UTF-16-encoded form of a surrogate pair of two 16-bit code units:

JS 术语中的“char”实际上是一个 UTF-16 代码单元,而不是完整的 Unicode 字符。(这种可悲的事态起源于没有区别的古代*。)要使用基本多语言平面之外的字符,您必须以 UTF-16 编码形式编写两个 16代理对-位代码单元

String.fromCharCode(0xD83D, 0xDE04)

In ECMAScript 6 we will get some interfaces that let us deal with strings as if they were full Unicode code points, though they are incomplete and are only a fa?ade over the String type which is still stored as a code unit sequence. Then we'll be able to do:

在 ECMAScript 6 中,我们将获得一些接口,让我们可以像处理完整的 Unicode 代码点一样处理字符串,尽管它们是不完整的,并且只是对仍作为代码单元序列存储的 String 类型的一种伪装。然后我们将能够做到:

String.fromCodePoint(0x1F604)

See this questionfor some polyfill code to let you use this feature in today's browsers.

请参阅此问题以获取一些 polyfill 代码,以便您在当今的浏览器中使用此功能。

(*: When I get access to a time machine I'm leaving Hitler alone and going back to invent UTF-8 earlier. UTF-16 must never have been!)

(*:当我使用时间机器时,我将让希特勒一个人呆着,回到更早的时候发明 UTF-8。UTF-16 绝对不是!)

回答by Thomas P.

You can also use the hacky method if you don't want to include String.fromCodePoint()in your code. It consists in creating a virtual element ...

如果您不想包含String.fromCodePoint()在代码中,也可以使用 hacky 方法。它包括创建一个虚拟元素......

elem=document.createElement('p')

elem=document.createElement('p')

... Filling it with the Working HTML...

... 用工作 HTML 填充它...

elem.innerHTML = "&#x1f604"

elem.innerHTML = "&#x1f604"

... And finally getting its value

... 最终得到它的价值

value = elem.innerHTML

value = elem.innerHTML

To make it short, this works because of the fact that, as soon as you set the value of a HTML container, the value gets converted into the corresponding character.

简而言之,这是因为一旦您设置了 HTML 容器的值,该值就会被转换为相应的字符。

Hope I could help.

希望我能帮上忙。