css - matchmedia polyfill 工具

标签 css media-queries polyfills

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

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

paulirish 也可以用另一种类似的方式实现它,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';
            }
        };

最佳答案

两者的工作方式相同。

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

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

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

相关文章:

JavaScript 为 event.key 警报 event.keyCode 制作基本的polyfill,以实现 Chrome 的现代化

javascript - 是否有(polyfill)代码可以重置给定元素上所有继承的 CSS 属性?

css - 带有超链接的文本没有颜色变化

html - 未应用溢出的嵌套 flexbox 中的 CSS

html - 为什么我的网站布局分崩离析?

css - 为什么我的简单媒体查询在模拟手机时会产生滚动条

html - 带有 em 的 SVG 高度没有响应

css - 默认 CSS 覆盖媒体查询

javascript - 检测 geo-uri 支持

html - 如何设置设备最小宽度和缩放较低的宽度