用JavaScript和HTML打印emojis [英] Printing emojis with JavaScript and HTML

查看:106
本文介绍了用JavaScript和HTML打印emojis的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 < p id =emoji>&#x1f604;< / p为H. 

这并不是:

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


解决方案

JS中的'char'实际上是一个UTF -16代码单元,而不是完整的Unicode字符。 (这种令人悲伤的事态源自古代,当时没有区别*)。要使用基本多语言平面以外的字符,必须以UTF-16编码形式写入两个16位代码单元的代理对

  String.fromCharCode(0xD83D,0xDE04)



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

$ p $ String.fromCodePoint(0x1F604)

有关某些polyfill代码,请参阅此问题让我们在今天的浏览器中使用这个功能。



(*:当我访问时间机器时,我将离开希特勒并且早一点发明UTF-8 。UTF-16绝不可能!)


Why does this work:

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

And this doesn't:

document.getElementById("emoji").innerHTML = String.fromCharCode(parseInt('1f604', 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)

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)

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

(*: 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打印emojis的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆