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

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

提交回复
热议问题