我可以使用javascript / jQuery更改媒体查询吗? [英] Can I change the media query using javascript / jQuery?

查看:86
本文介绍了我可以使用javascript / jQuery更改媒体查询吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有媒体查询的style.css。在我的JavaScript文件中,我为存储在变量中的所需移动宽度设置了一个值。

通过更改变量,我想更改媒体的值自动查询。是否有可能改变.css文件的内容与JavaScript一样,我可以改变DOM?
使用javascript向DOM添加HTML < style> -element并不是我想要的解决方案,因为我想将所有css保存在.css文件中

解决方案

最好的选择是有两组媒体查询,它们仅基于存在的父类应用。 / p>

  @media(max-width:600px){

.w600 .myDiv {
红色;
}

}

@media(max-width:400px){

.w400 .myDiv {
color :红;
}

}

然后你可以添加/ code> w600 或 w400 添加到 body 类以允许所需的媒体查询工作。



使用jQuery可以这样做:

  $(body)。addClass(w600)
.removeClass(w400);






我感谢您可能不止一种风格因此希望减少代码重复。

在这种情况下,您可以使用CSS转译器,例如 Less with mixins:

  @mediaqueryruleset:{
.myDiv {
颜色:红色;
}
.myOtherDiv {
color:blue;



@media(max-width:600px){
$ b $ .w600 {
@mediaqueryruleset();
}

}

@media(max-width:400px){

.w400 {
@mediaqueryruleset( );
}

}

会输出:

  @media(max-width:600px){
.w600 .myDiv {
color:red;
}
.w600 .myOtherDiv {
color:blue;
}
}
@media(max-width:400px){
.w400 .myDiv {
color:red;
}
.w400 .myOtherDiv {
color:blue;
}
}


I have a style.css with a media query. In my javascript-file, I have a value for the desired mobile-width stored in a variable.

By changing the variable, I want to change the value of the media query automatically. Is it somehow possible to alter the contents of the .css-file with javascript like I can change the DOM? Adding a HTML <style>-element to the DOM using javascript is not my desired solution, because I want to keep all css in the .css-file

解决方案

The best option would be to have two sets of media queries which are only applied based on a parent class being present.

@media (max-width: 600px) {

  .w600 .myDiv{
    color:red;
  }

}

@media (max-width: 400px) {

  .w400 .myDiv{
    color:red;
  }

}

You could then add/remove w600 or w400 to the body class to allow the required media query to work.

Using jQuery this could be done like:

$("body").addClass("w600")
         .removeClass("w400");


I appreciate you may have more than just one style and would therefore like to reduce code duplication.

In which case you could use a CSS transpiler such as Less with mixins:

@mediaqueryruleset:{
  .myDiv{
    color:red;
  }
  .myOtherDiv{
    color:blue;
  }
}

@media (max-width: 600px) {

  .w600 {
    @mediaqueryruleset();
  }

}

@media (max-width: 400px) {

  .w400 {
    @mediaqueryruleset();
  }

}

Which would output:

@media (max-width: 600px) {
  .w600 .myDiv {
    color: red;
  }
  .w600 .myOtherDiv {
    color: blue;
  }
}
@media (max-width: 400px) {
  .w400 .myDiv {
    color: red;
  }
  .w400 .myOtherDiv {
    color: blue;
  }
}

这篇关于我可以使用javascript / jQuery更改媒体查询吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆