IE problems with Media Queries
OK, this script checks the media type using css media queries. The idea is that I create a div (pre-DOM) and a style element with m开发者_StackOverflowedia queries, and if the style is applied then the media query was true. This works in Firefox 5, but not in IE 9.
/** Detect Browser Media **/
if(!window.mediaQuery){
window.mediaQuery = function(query){
var boolean = 0;
style = document.createElement('style');
style.media = query;
style.innerHTML = '#mediaQuery{width:5px;}';
document.head.appendChild(style);
div = document.createElement('div');
div.id = 'mediaQuery';
document.documentElement.appendChild(div);
if(div.offsetWidth == 5){boolean = 1;}
console.log(div.offsetWidth," ",boolean);
return { match:boolean };
}
}
This returns "5 1" in FF 5 and in Chrome console, but it returns "919 0" in IE 9. What is IE doing here? How can I work around?
Here is an example of the function call: mediaQuery('screen and (min-width: 480px)').match
After some testing I have found that the width matches 100% of the screen width. Why isn't the media query working in IE, it works in FF and Chrome... Maybe IE is just not processing the CSS before I test the width in javascript?
I figured this out.
IE only applies css to elements in the body, in order to get it to use the css you have to place the div within a fake body (because the real body hasn't loaded yet). Here is the finished script:
/** Detect Browser Media **/
if(!window.mediaQuery){
window.mediaQuery = function(query){
var boolean = 0;
var style = document.createElement('style');
style.type="text/css";
style.media = query;
if(style.styleSheet){style.styleSheet.cssText='#mediaQuery{width:30px;}';}else{
var MyCssText=document.createTextNode("#mediaQuery{width:30px;}");
style.appendChild(MyCssText);
}
document.head.appendChild(style);
bod = document.createElement('body');
bod.id="fakeBody";
div = document.createElement('div');
div.id = 'mediaQuery';
document.documentElement.appendChild(bod);
bod.appendChild(div);
if(div.offsetWidth == 30){boolean = 1;}
console.log(div.offsetWidth," ",boolean);
return { match:boolean };
}
}
精彩评论