Detect dynamic media queries with JavaScript?

前端 未结 4 810
误落风尘
误落风尘 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 07:12

    I managed to get the breakpoint values by creating width rules for invisible elements.

    HTML:

    CSS:

    $grid-breakpoints: (
        xs:   0,
        tiny: 366px,
        sm:   576px,
        md:   768px,
        lg:   992px,
        xl:   1200px
    );
    
    .secret-media-breakpoints {
        display: none;
    
        @each $break, $value in $grid-breakpoints {
            .#{$break} {
                width: $value;
            }
        }
    }
    

    JavaScript:

    app.breakpoints = {};
    $('.secret-media-breakpoints').children().each((index, item) => {
        app.breakpoints[item.className] = $(item).css('width');
    });
    

提交回复
热议问题