简体   繁体   中英

Media query using jquery

I am using the same view page (with CSS) in 3 different areas where resolutions are different. My problem is that I want some block of media query at some condition only.

Like:

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 
}
}

Is this possible?

I think Crossfire's suggestion is probably the best. Just add a class to your HTML tag based on the conditions.

If you're looking for a JS only solution, you can use window.matchMedia

For instance:

 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 
     }
 } 

This is basically a media query in JS and it also pretty much works the same. Please note that this solution is not supported in IE9 or lower.

Edit: here's a solution that also works in IE9 or lower. What this does is simply call the function on window resize or load. Then you can add in conditions as you wish. You should be able to work with this.

  $(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();});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM