假设我想动态添加与媒体条件相关的 CSS 规则。例如,如下所示:
@media only screen and (min-device-width : 500px){
.someClass: {
color: blue;
}
}
一个合乎逻辑的步骤是使用 JavaScript 检查媒体查询的有效性,并在测试通过时插入规则。类似以下内容:
if(matchMedia(only screen and (min-device-width : 500px))){
$('.someClass').css('color', 'blue');
}
缺点是规则不会响应。如果我改变屏幕尺寸,蓝色不会相应改变。我可以为屏幕尺寸的变化添加一个监听器,但我认为这有点矫枉过正。
我的问题是:有没有办法通过 Javascript 或 JQuery 添加响应式规则?
最佳答案
您想了解 enquire.js :
enquire.register("screen and (max-width:1000px)", {
match : function() {}, // REQUIRED
// Triggered when the media query transitions
// *from an unmatched state to a matched state*
unmatch : function() {}, // OPTIONAL
// If supplied, triggered when the media query transitions
// *from a matched state to an unmatched state*.
setup : function() {}, // OPTIONAL
// If supplied, a one-time setup function
// triggered when the handler is first registered.
deferSetup : true, // OPTIONAL, defaults to false
// If set to true, defers execution the setup function until
// the media query is first matched. Setup is still triggered just once.
destroy : function() {} //OPTIONAL
// If supplied, triggered when a hander is unregistered (covered later).
// Enables you to provide lifecycle to responsive widgets.
// Put cleanup logic here.
}).listen(); // More on this next
[来自文档]
编辑:如果你想通过 js 添加纯 CSS 规则 [不依赖监听器],我认为这是不可能的。
关于javascript - 使用 Javascript 或 JQuery 插入响应式 CSS 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14770869/