matchmedia polyfill工具

时间:2015-05-12 06:39:26

标签: css3 media-queries polyfills

如何以及为什么polyfill可以工作?

<uses-permission android:name="android.permission.CAMERA" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="18" />
<uses-permission
    android:name="android.permission.READ_EXTERNAL_STORAGE"
    android:maxSdkVersion="18" />

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

密钥代码如下

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 ));

1 个答案:

答案 0 :(得分:0)

两者的工作方式相同。

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

如果元素的宽度确实是预定义的宽度,则媒体正在工作且函数的计算结果为真