html - 如果 HTML5 的默认字符编码是 UTF-8,为什么需要在 HTML5 文档中指定字符编码?

标签 html unicode encoding utf-8 character-encoding

我已关注 HTML5 文档 :

<!DOCTYPE html>
<html>
    <head> </head>
    <body>
        <p>Beträge: 20€</p>
    </body>
</html>

上述 cod 的输出如下:
Beträge: 20€

我在下面试过的 HTML5 代码 :
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <p>Beträge: 20€</p>
    </body>
</html>

上面的代码给了我预期的以下输出:
Beträge: 20€

据我所知, 的默认字符编码HTML5 UTF-8 .它的默认值意味着它不应在 <meta> 中明确指定标签。

所以,在我的第一个代码片段中,我跳过了代码 <meta charset="UTF-8">但是我得到了一些奇怪的意外结果。

然后,我尝试添加代码 <meta charset="UTF-8">中间<head>一对标签,它工作得非常好,我得到了预期的结果。

所以,我的问题是因为 中的默认字符编码HTML5 已设置为 UTF-8 如果没有明确指定,为什么它不起作用?

为什么需要指定字符编码 “UTF-8” HTML5 文档?

最佳答案

HTTP1.1 specifies除非另有说明,否则浏览器应将所有文本视为 ISO-8859-1:

When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1"


同时,HTML5 规定

If the transport layer specifies an encoding, and it is supported, return that encoding with the confidence certain, and abort these steps.


因此,HTTP1.1 默认为 ISO-8859-1,并覆盖其他所有内容。
如果你编码
Beträge: 20€
使用 UTF-8,然后将其解码为 ISO-8859-1,您将得到准确的乱码输出:
Beträge: 20â¬
如以下代码片段所示(Java,并不重要):
new String("Beträge: 20€".getBytes("utf-8"), "iso-8859-1")
// result: Beträge: 20â¬
浏览器实际上确实会警告您。例如。 Firefox 在控制台中显示以下警告:

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.


要获得正确的输出,您必须通过 UTF-8 手动覆盖 ISO-8859-1(在 Firefox 的情况下,它位于 View -> Text Encoding -> Unicode (而不是“Western ”下) ))。

所以,总结一下:我什至看不到它在哪里说“HTML5 的默认字符编码是 UTF-8”。它所说的似乎是:

Authors are encouraged to use UTF-8. Conformance checkers may advise authors against using legacy encodings.

关于html - 如果 HTML5 的默认字符编码是 UTF-8,为什么需要在 HTML5 文档中指定字符编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52351400/

相关文章:

python - Python 中的 Unicode 到原始字符

javascript - HTML页面编码问题

javascript - 使用 JQuery 删除空的 tbody

html - 如何覆盖 MVC Razor 中的@section

jquery - 如何在页面加载前运行加载动画

.net - 使用ASCII编码通过WebSphere MQ将消息发送到SWIFT

Python 编码问题

javascript - 为什么我的事件没有为两个订阅者触发?

python : working with german umlaut

javascript - Erlang 中的 decodeURIComponent