您可以通过JavaScript将媒体查询特定样式应用于HTML元素吗?

时间:2012-05-01 17:58:01

标签: javascript html css media-queries

传统上,您可以使用JavaScript将样式应用于元素:

document.body.style.color = "red";

但是你能以类似的方式应用媒体查询特定的风格吗?我所说的是:

body {
  color: red;
}

@media only screen and (max-width : 320px) {
  body {
    color: blue;
  }
}

上面的@媒体特定风格。这可以通过JavaScript以编程方式应用于元素吗?例如,我想将上述样式应用于body元素,但不指定任何CSS。我想用JavaScript完成所有操作。这是否可能(以跨浏览器的方式)?

1 个答案:

答案 0 :(得分:0)

在加载窗口和调整窗口大小时检查窗口的宽度。基本理念:

function resized() {
  var myWidth = 0, 
      myHeight = 0,
      color = "red";
  if( typeof( window.innerWidth ) == 'number' ) {
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }

  if (myWidth <= 320) {
      color = "blue";
  }
  document.body.style.color = color;
}
window.onresize = resized;
resized();