使用jquery进行媒体查询

时间:2015-02-02 09:51:37

标签: jquery css media-queries media

我在3个不同区域使用相同的视图页面(使用CSS),其中分辨率不同。我的问题是我只想在某种情况下查询一些媒体块。

像:

if( a == 20)
{
@media (max-width : 900px) and (min-width :500px){
// some code 
}
}
if( a == 40)
{
@media (max-width : 900px) and (min-width :500px){
// some code 
}
}

这可能吗?

1 个答案:

答案 0 :(得分:0)

我认为Crossfire的建议可能是最好的。只需根据条件向HTML标记添加一个类。

如果您正在寻找仅限JS的解决方案,则可以使用window.matchMedia

例如:

 if( a == 20)
 {
     window.matchMedia('screen and (max-width: 900px) and (min-width:500px)') 
     {
     // some code 
     }
 }
 if( a == 40)
 {
     window.matchMedia('screen and (max-width: 900px) and (min-width:500px)')
     {
     // some code 
     }
 } 

这基本上是JS中的媒体查询,它的工作方式也相同。请注意,IE9或更低版本不支持此解决方案。

编辑:这是一个也适用于IE9或更低版本的解决方案。这样做只需在窗口调整大小或加载时调用该函数。然后您可以根据需要添加条件。你应该可以使用它。

  $(function() {

      window.responsive = function responsive() {
         //get the width of the window
         var width = $(window).width();

         if (width > 500 && width < 900) {
                //width is larger than 500px and smaller than 900px
                $('div').addClass('md-screen');
         }
       }

  });
  //Call the function on load and resize
  $(window).on('ready load resize orientationchange',function(){responsive();});