简体   繁体   中英

How do I add media Queries into Jquery

Is it possible to add media jquery's into your jquery code?

I need to reduce "slideWidth: 83," when my screen hits a size of 800px;

$(document).ready(function(){
  $('.slider4').bxSlider({
    slideWidth: 83,
    minSlides: 2,
    maxSlides: 9,
    moveSlides: 1,
    slideMargin: 15
  });
});

Media queries are supported in js via window.matchMedia

This allows you to create something like

var isPortrait = window.matchMedia("(orientation: portrait)");
if (isPortrait.matches){
    // Screen is portrait
}

or

var smallScreen = window.matchMedia("(max-width: 480px)");
if (smallScreen.matches){
    // Screen is less than 480px
}

Support is good within modern browsers and there is a polyfill available as well but it doesn't support resizing out of the box.

More info – https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia

No, but you can measure the current width of the window and configure your code based on that:

if ($(window).width()<768) {
   // do whatever
}

If you need it to be responsive, tie your code to the window.onresize event as well:

$(window).on('resize', function() {
    if ($(window).width()<768) {
        // do whatever
    }
});

You cant explicitly have media queries, but you can check the window width with this little code :

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

I cant remember where I found this code so i can't give the credit...

Anyway, use the window resize event to check the width like that :

$(window).resize(function(){
    if(viewport().width > x && viewport().width < y){
        //do something
    }
}).trigger('resize');

You can use Paul Irish's MatchMedia.js polyfill to do Javascript media queries but it will not work in IE9 and earlier. Still it's quite useful and you can conditionally handle IE with a less precise method (like $(window).width() ).

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