原标题:link标签和script标签跑到body下面,网页顶部有空白,出现“锘匡豢”乱码,UTF-8 BOM,EF BB BF
来自:http://tunps.com/link-and-script-goes-under-body-tag
最近在做一个简单的记账系统,用php+mysql。在要完工的时候发现了一个问题,研究了2天的时间才有了答案。
以下是页首的裁图:
页面的头部有空白区域。有的人可能怀疑是css的margin,padding,border没有重置为0造成的。其实不然,我已经将这几个属性重置为0。
而且在firebug下面查看HTML代码会发现link标签和script表情跑到body下面:
并且body标签下面和link标签之间有空行。
我自诩的查看我的模板文件是没有任何问题的,想了很久最后实在是没辙了,跑到Stackoverflow高手云集的地方去提问。
有个人提出了是页面中存在stray text。
You've got some stray text content inside the , before the tag. The browser sees the text and decides this means you're starting the main document body but have forgotten to include the tag.
This is actually valid—if inadvisable—in HTML4: the end-tag and start-tag are both optional. This is how you can have just Hello! as a valid HTML document. But it's not permissible in XHTML, so if you validate your document you should get a “character data is not allowed here” error at the point the stray text occurs.
The browser then parses the rest of the document as body content, putting the inside the body (which is not valid, but which is nonetheless commonplace). It ignores the real when that comes along because it already has a body.
If you can't see the stray text, perhaps it's an invisible character like U+00A0 No-break space or—most likely for Chinese documents—U+3000 Ideographic space , which you may get when you press space in some input method modes. These characters won't be visible, but they're not ‘ignorable whitespace’ like a normal U+0020 Space or newline, so they trigger ‘text content’ processing and force the .
就是说页面存在浏览器不能忽略的空白,比如U+0020活U+3000之类的。
我的php脚本全部使用的是utf-8编码,html页面的charset也就是utf-8,我强制让浏览器把页面用其他编码来解析,比如GB2312,然后出现了如下图的情况:
空白的部分出现了乱码,而且内容都是“锘匡豢”,这下子更是把我搞糊涂了。我按照SO上面bobince兄的建议,把模板页传到W3C markup validator上面去检查,得出来如下结论:
大概意思是说,UTF-8中的BOM编码在一些编辑器或者是浏览器中支持不好,可能会出现问题。
然后网上搜索了关于Byte Order Mark的信息:
在UCS 编码中有一个叫做"ZERO WIDTH NO-BREAK SPACE"的字符,它的编码是FEFF。而FFFE在UCS中是不存在的字符,所以不应该出现在实际传输中。UCS规范建议我们在传输字节流前,先传输字符"ZERO WIDTH NO-BREAK SPACE"。这样如果接收者收到FEFF,就表明这个字节流是Big-Endian的;如果收到FFFE,就表明这个字节流是Little- Endian的。因此字符"ZERO WIDTH NO-BREAK SPACE"又被称作BOM。
UTF-8不需要BOM来表明字节顺序,但可以用BOM来表明编码方式。字符"ZERO WIDTH NO-BREAK SPACE"的UTF-8编码是EF BB BF。所以如果接收者收到以EF BB BF开头的字节流,就知道这是UTF-8编码了。
Windows就是使用BOM来标记文