gpt4 book ai didi

css - matchmedia polyfill 工具

转载 作者:行者123 更新时间:2023-11-28 07:54:50 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com