Twitter Bootstrap - how to detect when media queries starts

后端 未结 16 755
抹茶落季
抹茶落季 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:43

    Using jquery you can find the size of current window and then accordingly do your stuff.

    $(window).resize(function() {
      if ($(this).width() >= 1280) {
        //do something
      }
      else if ($(this).width() < 1280 && $(this).width()>= 980) {
        //do something
      }
      ...
    });
    

    CSS:: Twitter-Bootsrap-layouts

    /* Large desktop */
    @media (min-width: 1200px) { ... }
    
    /* Portrait tablet to landscape and desktop */
    @media (min-width: 768px) and (max-width: 979px) { ... }
    
    /* Landscape phone to portrait tablet */
    @media (max-width: 767px) { ... }
    
    /* Landscape phones and down */
    @media (max-width: 480px) { ... }
    
    0 讨论(0)
  • 2020-12-14 02:43

    One issue with the other answers is the change event is triggered EVERY resize. This can be very costly if your javascript is doing something significant.

    The code below calls your update function only one time, when a threshold is crossed.

    To test, grab your window size handle, and drag resize it quickly to see if the browser chokes.

    <script>
    // Global state variable
    var winSize = '';
    
    window.onresize = function () {
        var newWinSize = 'xs'; // default value, check for actual size
        if ($(this).width() >= 1200) {
            newWinSize = 'lg';
        } else if ($(this).width() >= 992) {
            newWinSize = 'md';
        } else if ($(this).width() >= 768) {
            newWinSize = 'sm';
        }
    
        if( newWinSize != winSize ) {
            doSomethingOnSizeChange();
            winSize = newWinSize;
        }
    };
    </script>
    
    0 讨论(0)
  • 2020-12-14 02:44

    You can use matchMedia and a wrapper library enquire.js which registers media queries and emits events when they are matched/unmatched.

    Usage

    Let's use these Bootstrap CSS media queries as an example taken from the docs.

    /* Extra small devices (phones, less than 768px) */
    /* No media query since this is the default in Bootstrap */
    
    /* Small devices (tablets, 768px and up) */
    @media (min-width: @screen-sm-min) { ... }
    
    /* Medium devices (desktops, 992px and up) */
    @media (min-width: @screen-md-min) { ... }
    
    /* Large devices (large desktops, 1200px and up) */
    @media (min-width: @screen-lg-min) { ... }
    

    To see when each of these rules get applied, use enquire.js to register the media queries and supply appropriate match and unmatch functions, as below:

    let rules = [
        '(max-width: 768px)',  // extra small devices, default
        '(min-width: 768px)',  // small devices
        '(min-width: 992px)',  // medium devices
        '(min-width: 1200px)'  // large devices
    ];
    
    for (let rule of rules) {
        enquire.register(rule, {
          match: function() {
            console.log(rule + ' matched');
          },      
    
          unmatch: function() {
            console.log(rule + ' unmatched');
          } 
        });
    }
    

    enquire.js uses matchMedia which supports only the modern browsers, no IE9 for example. So polyfill will be needed for legacy browsers to make this work.

    Demo

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

    I used this to only stick the navbar at https://ducttapedanyol.com in bootstrap on large screens:

    if ($(this).width() >= 979) { // Detect screen size
    $(document).ready(function () {
    
        var menu = $('.menu');
        var origOffsetY = menu.offset().top;
    
        function scroll() {
           if ($(window).scrollTop() >= origOffsetY) {
              $('.menu').addClass('sticky');
              $('.fix').addClass('fix-tall');
           } else {
              $('.menu').removeClass('sticky');
              $('.fix').removeClass('fix-tall');
           }
    
    
        }
    
        document.onscroll = scroll;
    
    });
    }
    
    0 讨论(0)
  • 2020-12-14 02:46

    this code add body tag ld, md, sd or xd class

         $(function(){
    
            var device_width_detect = '';
    
            function device_detec(){
                if ($(this).width() >= 1280) {
                    device_width_detect = 'ld';
                }else if ($(this).width() < 1280 && $(this).width()>= 992) {
                    device_width_detect = 'md';
                }else if ($(this).width() < 992 && $(this).width()>= 768) {
                    device_width_detect = 'sd';
                }else if ($(this).width() < 768) {
                    device_width_detect = 'xd';
                }
                $('body').removeClass( "ld md sd xd" ).addClass( device_width_detect );
            }
            device_detec();
            $(window).on('resize', device_detec);
    
        });
    
    0 讨论(0)
  • 2020-12-14 02:48

    I have prepered a super lightweight library to deal with events fired when window width and Bootstrap breakpoint is changed - responsive-breakpoint-tester

    var viewport = new ResponsiveTester();
    
    $('body').on('in.screen.xs', function(event, devices) {
        // Code executed when viewport is was changed to xs
    });
    
    $('body').on('out.screen.xs', function(event, devices) {
        // Code executed when viewport is no longer xs
    });
    

    Other features like current breakpoint check are also included:

    if (viewport.is('xs')) {
        // Executed only on xs breakpoint
    }
    
    if (viewport.is('!=xs')) {
        // Executed on all breakpoints that are not equal xs (sm, md, lg)
    }
    
    if (viewport.is('<md')) {
        // Executed on breakpoints that are smaller than md (xs, sm)
    }
    
    if (viewport.is('<=md')) {
        // Executed on breakpoints that are smaller or equal to md (xs, sm, md)
    }
    
    if (viewport.is('>md')) {
        // Executed on breakpoints that are larger than md (lg)
    }
    

    Bootstrap 4 and Foundation configuraions are supported, more info on GitHub Repository

    0 讨论(0)
提交回复
热议问题