Detect dynamic media queries with JavaScript?

前端 未结 4 783
误落风尘
误落风尘 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:10

    I found an hackish but easy solution :

    @media (min-width: 800px) {
    .myClass{
        transition-property: customNS-myProp;
    }
    

    this css property is just a markup to be able to know in JS if the breaking point was reached. According to the specs, transition-property can contain anything and is supported by IE (see https://developer.mozilla.org/en-US/docs/Web/CSS/transition-property and https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident).

    Then just check in js if transition-property has the value. For instance with JQuery in TS :

    const elements: JQuery= $( ".myClass" );
            $.each( elements, function (index, element) {
                const $element = $( element );
                const transition = $element.css( "transition-property" );
                if (transition == "custNS-myProp") {
                    // handling                     ...
                }
            });
    

    Of course there is a word of warning in the wiki that the domain of css property identifiers is evolving but I guess if you prefix the value (for instance here with customNS), you can avoid clashes for good.

    In the future, when IE supports them, use custom properties instead of transition-property https://developer.mozilla.org/en-US/docs/Web/CSS/--*.

提交回复
热议问题