使用 JavaScript 和 HTML 打印表情符号 [英] Printing emojis with JavaScript and HTML
问题描述
为什么这样做:
<p id="emoji">😄</p>
这不会:
document.getElementById("emoji").innerHTML = String.fromCharCode(parseInt('1f604', 16));
推荐答案
JS 术语中的char"实际上是一个 UTF-16 代码单元,而不是一个完整的 Unicode 字符.(这种可悲的状况源于没有区别的古代*.)要使用基本多语言平面之外的字符,您必须以 两个 16 位代码单元的代理对:
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:
String.fromCharCode(0xD83D, 0xDE04)
在 ECMAScript 6 中,我们将获得一些接口,让我们可以像处理完整的 Unicode 代码点一样处理字符串,尽管它们是不完整的,并且只是 String 类型的一个外观,仍然作为代码单元序列存储.然后我们就可以做到:
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:
String.fromCodePoint(0x1F604)
请参阅这个问题,了解一些 polyfill 代码,让您可以在当今的浏览器中使用此功能.
See this question for some polyfill code to let you use this feature in today's browsers.
(*:当我可以使用时间机器时,我会让希特勒独自一人,回到更早的时候发明 UTF-8.UTF-16 绝对不是!)
(*: 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!)
这篇关于使用 JavaScript 和 HTML 打印表情符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!