Detect dynamic media queries with JavaScript?

前端 未结 4 781
误落风尘
误落风尘 2021-01-13 06:16

I\'ve been searching for a lightweight, flexible, cross-browser solution for accessing CSS Media Queries in JavaScript, without the CSS breakpoints being repeated in the Jav

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-13 06:54

    try this

    const mq = window.matchMedia( "(min-width: 500px)" );
    

    The matches property returns true or false depending on the query result, e.g.

    if (mq.matches) {
    
      // window width is at least 500px
    } else {
      // window width is less than 500px
    }
    

    You can also add an event listener which fires when a change is detected:

    // media query event handler
    if (matchMedia) {
      const 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
      }
    
    }
    

提交回复
热议问题