Is it possible to use css like media queries in javascript?

后端 未结 3 1683
春和景丽
春和景丽 2021-01-25 00:16

I am wondering if there is a way to use media queries in javascript like i use it in CSS ? i want to handle device-width or orientation and fire a fun

相关标签:
3条回答
  • 2021-01-25 01:06

    Check out Responsive JavaScript. Sounds like it will do what you're looking for.

    0 讨论(0)
  • 2021-01-25 01:09

    Try to use matchMedia (jQuery)

    // media query event handler
    if (matchMedia) {
        var mq = window.matchMedia("(min-width: 500px)");
        mq.addListener(WidthChange);
        WidthChange(mq);
    }
    
    // media query change
    function WidthChange(mq) {
    
        if (mq.matches) {
            // window width is at least 500px
        }
        else {
            // window width is less than 500px
        }
    
    }
    
    0 讨论(0)
  • 2021-01-25 01:14

    I would suggest using window.matchMedia method , wich allows you to test for a particular media query and add an event listener whenever it's matched or not .

    Example :

    var mq = window.matchMedia("(max-width: 600px)");
    mq.addListener(function(event){
        if (event.matches) {
            console.log("Small Screen mode !");
        }
    });
    

    Example 2:

    onOrientationChange = function(event){
        if (event.matches) {
            console.log("Portrait mode!");
        }
    };
    
    var mq = window.matchMedia("(orientation: portrait)");
    mq.addListener(onOrientationChange);
    
    /* ... /*
    
    /* When you no longer need to receive notifications , you can remove the listener */
    
    mq.removeListener(onOrientationChange);
    

    This API is supported in : Chrome 9+ , Firefox 6+ , IE10+

    Additional info on MDN

    0 讨论(0)
提交回复
热议问题