填充料如何以及为什么可以工作?

w.matchMedia = w.matchMedia || (function( doc, undefined ) {

        var bool,
            docElem = doc.documentElement,
            refNode = docElem.firstElementChild || docElem.firstChild,
            // fakeBody required for <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 = "&shy;<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 ));


保罗还以另一种类似的方式实现它,https://github.com/paulirish/matchMedia.js/blob/master/matchMedia.js

关键代码如下

info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;

        styleMedia = {
            matchMedium: function(media) {
                var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';

                // 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
                if (style.styleSheet) {
                    style.styleSheet.cssText = text;
                } else {
                    style.textContent = text;
                }

                // Test if media query is true or false
                return info.width === '1px';
            }
        };

最佳答案

两者的工作方式相同。

他们只是注入您作为参数传递的媒体,并使用它来使用预定义的样式(第一个的宽度为42像素,第二个的宽度为1像素),

如果元素的宽度确实是预定义的宽度,则表明介质正在工作并且该函数的值为true

关于css - Matchmedia Polyfill工具,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30183550/

10-11 05:49