css3 - matchmedia polyfill implement -
how , why polyfill can work?
w.matchmedia = w.matchmedia || (function( doc, undefined ) { var bool, docelem = doc.documentelement, refnode = docelem.firstelementchild || docelem.firstchild, // fakebody required <ff4 when executed in <head> fakebody = doc.createelement( "body" ), div = doc.createelement( "div" ); div.id = "mq-test-1"; div.style.csstext = "position:absolute;top:-100em"; fakebody.style.background = "none"; fakebody.appendchild(div); return function(q){ div.innerhtml = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docelem.insertbefore( fakebody, refnode ); bool = div.offsetwidth === 42; docelem.removechild( fakebody ); return { matches: bool, media: q }; }; }( w.document ));
paulirish alse implement in similar way, https://github.com/paulirish/matchmedia.js/blob/master/matchmedia.js
the key code following
info = ('getcomputedstyle' in window) && window.getcomputedstyle(style, null) || style.currentstyle; stylemedia = { matchmedium: function(media) { var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }'; // 'style.stylesheet' used ie <= 8 , 'style.textcontent' other browsers if (style.stylesheet) { style.stylesheet.csstext = text; } else { style.textcontent = text; } // test if media query true or false return info.width === '1px'; } };
both work same way.
they inject media pass parameter, , use aply predefined style (a width of 42 px first, , of 1px second),
if width of element predefined one, media working , function evaluates true
Comments
Post a Comment