If doctype is <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
// do something
else
// do something
怎么做?
谢谢。
最佳答案
是的,我在 IE、Chrome、Firefox 和 Opera 中测试过之后回来了。 IE 将通过以下代码为您提供完整的文档类型:
var doctype = document.documentElement.previousSibling.nodeValue;
// -> DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
不幸的是,这可能是不正确的,因为 Chrome、Firefox 和 Opera 对 nodeValue
返回 null
。由于它们都不支持 outerHTML
,我想不出一种方法来获取完整的文档类型,但您可以获取各个部分:
var doctype = document.documentElement.previousSibling;
console.log(doctype.systemId)
// -> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
console.log(doctype.publicId)
// -> -//W3C//DTD XHTML 1.0 Strict//EN
但是,这在 IE 中不起作用,但解析它们并不会太困难。您可以使用 if
语句检查 nodeValue
是否不 null
并回退到检查 systemId
或 publicId
.
用于运行测试的脚本:http://jsfiddle.net/Cwb8q/
关于jQuery 检查文档类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3043820/