插入文档的动态iframe为标准模式,默认为怪僻模式

Dynamic iframe inserted into document that is standards mode defaults to quirks mode

本文关键字:模式 默认 文档 标准 动态 iframe 插入      更新时间:2023-09-26

我有一个父文档,当前从document.compatMode返回CSS1Compat

当我添加一个空白的iframe jQuery像这样:

$("body").append("<iframe id='test-iframe'></iframe>");

并检查新iframe的compatMode,如下所示:

$("#test-iframe")[0].contentWindow.document.compatMode

它等于BackCompat

这会导致以后的大小写敏感问题和其他一些样式问题。我不能改变箱子,也不能控制它。新的iframe不应该是相同的compmode吗?有办法强迫它吗?

这是因为浏览器正在加载一个基本的html文档(注意没有doctype声明):

<html>
   <head></head>
   <body></body>
</html>

由于没有doctype声明Chrome将使用BackCompat模式

如果你想改变它的模式,要么将src url设置为使用doctype声明的html页面,要么写入iframe并将html设置为具有doctype声明的html。

var myContent = '<!DOCTYPE html><html><head></head><body></body></html>';
$("body").append("<iframe id='test-iframe'></iframe>");
var frame = $("#test-iframe")[0];
frame.contentWindow.document.open('text/htmlreplace');
frame.contentWindow.document.write(myContent);
frame.contentWindow.document.close();
console.log( frame.contentWindow.document.compatMode );

JSFiddle