How to get browser “Document Mode”

2020-02-28 04:31发布

I am developing some kind of JavaScript library. And i cause the problem that i have some specific issues for: Browser : IE8 / IE9 and Document Mode : IE7 I found the solution, but i don't want to use it in all situation, and want to use it just when i have the situation described above. I know that I can recognize browser by using:

return navigator.userAgent.toLowerCase().indexOf('MSIE 8') > -1;

But i recognize just browser version in such way but not the document mode, and i don't want to use my solution when I have, for example, browser mode IE8 and document mode IE 8. Is there a way to get page document mode in IE? Thanks in advance.

2条回答
地球回转人心会变
2楼-- · 2020-02-28 04:57

You can use document.documentMode to return exactly what document mode IE is using.

Meaning that if you have your browser mode set to IE9, but your document mode to IE8 it will return document.documentMode == 8 (while the userAgent string will still show up as IE9). This is particularly useful if your JS ever includes styling changes as it is the document mode that determines how IE renders a page, not the browser mode. Compatibility mode really just changes the document mode (usually to IE7).

In the few cases I've needed to I've just used something like this to differentiate IE's:

if (document.documentMode == 7) {
    doSomethingIn.IE7_only;
} else {
    doSomething.everwhereElse;
}

Hope that helps some.

查看更多
祖国的老花朵
3楼-- · 2020-02-28 05:04

I don't know how to retrieve the document mode1, but it may be wise to address the problem in a more basic way. Let's say you wanted to use document.querySelector in your scripting. That would fail in IE8/document mode IE7 Standards. So an additional check for the existence of document.querySelector itself would be the solution:

return ~navigator.userAgent.toLowerCase().indexOf('MSIE 8') 
       && document.querySelector; //=> IE8 and Docmode IE7 => false

1 Found a way to check for document mode: use document.documentMode. It returns an integer (so 7 for document mode IE7 standards), 5 for Quirks mode. It will be undefined for non IE browsers.

查看更多
登录 后发表回答