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

后端 未结 3 1682
春和景丽
春和景丽 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: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

提交回复
热议问题