Twitter Bootstrap - how to detect when media queries starts

后端 未结 16 754
抹茶落季
抹茶落季 2020-12-14 02:19

which is the fastest and easy way to fire when bootstrap-responsive.css media queries go in action?

go in action = when you resize window to mobile width and site is

相关标签:
16条回答
  • 2020-12-14 02:30

    This works for me in combination with Bootstrap 3:

    <div id="media-width-detection-element"></div>
    <style type="text/css">
        #media-width-detection-element {
            display: none;
            width: 0px;
        }
        @media (min-width: 768px) {
            #media-width-detection-element {
                width: 768px;
            }
        }
        @media (min-width: 992px) {
            #media-width-detection-element {
                width: 992px;
            }
        }
        @media (min-width: 1200px) {
            #media-width-detection-element {
                width: 1200px;
            }
        }
    </style>
    <script type="text/javascript">
        //<![CDATA[
        function xs() {
            return $("#media-width-detection-element").css("width") === "0px";
        }
        function sm() {
            return $("#media-width-detection-element").css("width") === "768px";
        }
        function md() {
            return $("#media-width-detection-element").css("width") === "992px";
        }
        function lg() {
            return $("#media-width-detection-element").css("width") === "1200px";
        }
        //]]>
    </script>
    

    The hidden DIV change width depending on the actual CSS min-width settings in use. Then my javascript simple check the current with of the DIV.

    0 讨论(0)
  • 2020-12-14 02:30

    here is my solution for bootstrap 4, based on @falsarella idea

    *note: use "full page" option below for test this snippet, otherwise it will return wrong screen type, based on snippet iframe size

    /**
     * @returns STRING current screen type like: xs, sm, md, lg or xl
     */
    function getScreenType() {
    
      !function initHelpers() {
        if ($('div.mq-detector').length !== 0) return;
        $('body').append(_mqDetector());
        // helpers
        function _mqDetector() {
          return `
          <div class="mq-detector invisible">
            <div
              class="d-block d-sm-none"
              data-type="xs"></div>
            <div
              class="d-none d-sm-block d-md-none"
              data-type="sm"></div>
            <div
              class="d-none d-md-block d-lg-none"
              data-type="md"></div>
            <div
              class="d-none d-lg-block d-xl-none"
              data-type="lg"></div>
            <div
              class="d-none d-xl-block"
              data-type="xl"></div>
          </div>
          `;
        }
      }();
    
      // @then
    
      return $('div.mq-detector').children().filter(':visible').data('type');
    
    }
    
    console.log(getScreenType())
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

    0 讨论(0)
  • 2020-12-14 02:31

    This already answered on stackoverflow from Terryfrancis is still useful in my Bootstrap 4 application, when I wanted to change the class of a non-bootstrap module into .col-md in my Bootstrap 4 application.

    I used both onload and window resize function:

    // on load
    if ($(window).width() > 575 && $(window).width() < 992) {
       $('div').addClass('col-md-6').removeClass('col-md-4');
    } else if ($(window).width() > 992) {
        $('div').addClass('col-md-4').removeClass('col-md-6');
    }
    
    // on user resizes browser window
     $( window ).resize(function() {
    if ($(window).width() > 575 && $(window).width() < 992) {
       $('div').addClass('col-md-6').removeClass('col-md-4');
    } else if (jQuery(window).width() > 992) {
        $('div').addClass('col-md-4').removeClass('col-md-6');
    }
    });
    
    0 讨论(0)
  • 2020-12-14 02:36

    I'd use window.matchMedia with window.addEventListener('resize'). Example below, specifically function getActiveBreakpoint() will tell you which breakpoint is active, but will also tell you which ones are lt- (less then) and gt- (greater then) in form of helper classes i.e. gt-xs gt-sm md lt-lg lt-xl, see https://jsfiddle.net/Lqtmc8yo/1/

    /*
    // from bootstrap/scss/_variables.scss
    $grid-breakpoints: (
        xs: 0,
        sm: 576px,
        md: 768px,
        lg: 992px,
        xl: 1200px
      ) !default;
    */
    
    const breakpoints = {
        xs: 0,
        sm: 576,
        md: 768,
        lg: 992,
        xl: 1200,
    }
    const orderedKeys = ['xs', 'sm', 'md', 'lg', 'xl']
    
    const getActiveBreakpoint = () => {
        let breakpoint = ''
        let classList = []
    
        orderedKeys.some((k, i) => {
            const n = orderedKeys[i + 1]
            let query = ''
            query += `(min-width: ${breakpoints[k]}px)`
            if (n) {
                query += `and (max-width: ${breakpoints[n] - 1}px)`
            }
            if (window.matchMedia(query).matches) {
                breakpoint = k
                classList = [...orderedKeys.slice(0, i).map(b => `gt-${b}`), k, ...orderedKeys.slice(i + 1, orderedKeys.length).map(b => `lt-${b}`)]
                return true
            }
            return false
        })
        return { breakpoint, classList, className: classList.join(' ') }
    }
    
    
    const calculate = () => {
      const result = getActiveBreakpoint()
      document.getElementById('result').innerHTML = `
           breakpoint: ${result.breakpoint}
           <br>
           className: ${result.className}
         `
    }
    
    window.addEventListener('resize', calculate)
    calculate()
    <div id="result"></div>

    0 讨论(0)
  • 2020-12-14 02:37

    Based on @falsarella's solution, the js part can be simplified to:

    var currMqIdx = undefined;
    var checkForResize = function() {    
        currMqIdx = $('#mq-detector span').index($('#mq-detector span:visible'));
    };
    
    $(window).on('resize', checkForResize);
    checkForResize();
    

    currMqIdx would be an int value, from 0 to 3. The bigger currMqIdx is, the wider the media is.

    0 讨论(0)
  • 2020-12-14 02:41

    I have revised codes in this link to Bootsrap 4 not alpha or beta. Codes as below;

        /* **********************************************************
            Detect bootrap 4 media query type
            https://getbootstrap.com/docs/4.0/utilities/display/
       ********************************************************** */
    
    
        $("body").append("<div style='visibilty:hidden' class='viewport-check'><span class='d-block d-sm-none'>xs</span><span class='d-none d-sm-block d-md-none'>sm</span><span class='d-none d-md-block d-lg-none'>md</span><span class='d-none d-lg-block d-xl-none'>lg</span><span class='d-none d-xl-block'>xl</span></div>");
    
        var Bootstrap4MediaQuery = "";
    
        //> Checks if the span is set to display block via CSS
        function FnDetectMediaQuery(_QsTarget) {
            var _QsTarget = $(_QsTarget).css('display') == 'block';
            return _QsTarget;
        }
    
        if(FnDetectMediaQuery('.viewport-check .d-block') == true)
        {
            Bootstrap4MediaQuery = "xs";
        }
        else if(FnDetectMediaQuery('.viewport-check .d-sm-block') == true)
        {
            Bootstrap4MediaQuery = "sm";
        }
        else if(FnDetectMediaQuery('.viewport-check .d-md-block') == true)
        {
            Bootstrap4MediaQuery = "md";
        }
        else if(FnDetectMediaQuery('.viewport-check .d-lg-block') == true)
        {
            Bootstrap4MediaQuery = "lg";
        }
        else if(FnDetectMediaQuery('.viewport-check .d-xl-block') == true)
        {
            Bootstrap4MediaQuery = "xl";
        }
        else
        {
            Bootstrap4MediaQuery = "";
        }
    
        console.log("Bootstrap4MediaQuery: " + Bootstrap4MediaQuery);
    
    0 讨论(0)
提交回复
热议问题