如何使用 JavaScript 检测 Twitter Bootstrap 3 的响应断点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18575582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:27:00  来源:igfitidea点击:

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

javascripttwitter-bootstrap-3dom-events

提问by Rubens Mariuzzo

Currently, Twitter Bootstrap 3 have the following responsive breakpoints: 768px, 992px and 1200px, representing small, medium and large devices respectively.

目前,Twitter Bootstrap 3 有以下响应断点:768px、992px 和 1200px,分别代表小型、中型和大型设备。

How can I detect these breakpoints using JavaScript?

如何使用 JavaScript 检测这些断点?

I would like to listen with JavaScript for all related events triggered when the screen change. And to be able to detect if the screen is for small, medium or large devices.

我想用 JavaScript 监听屏幕变化时触发的所有相关事件。并且能够检测屏幕是用于小型、中型还是大型设备。

Is there something already done? What are your suggestions?

有什么事情已经做了吗?你有什么建议?

回答by Maciej Gurban

Edit: This library is now available through Bower and NPM. See github repo for details.

编辑:这个库现在可以通过 Bower 和 NPM 获得。有关详细信息,请参阅 github 存储库。

UPDATED ANSWER:

更新的答案:

Disclaimer: I'm the author.

免责声明:我是作者。

Here's a few things you can do using the latest version (Responsive Bootstrap Toolkit 2.5.0):

以下是您可以使用最新版本 (Responsive Bootstrap Toolkit 2.5.0) 执行的一些操作:

// Wrap everything in an IIFE
(function($, viewport){

    // Executes only in XS breakpoint
    if( viewport.is('xs') ) {
        // ...
    }

    // Executes in SM, MD and LG breakpoints
    if( viewport.is('>=sm') ) {
        // ...
    }

    // Executes in XS and SM breakpoints
    if( viewport.is('<md') ) {
        // ...
    }

    // Execute only after document has fully loaded
    $(document).ready(function() {
        if( viewport.is('xs') ) {
            // ...
        }
    });

    // Execute code each time window size changes
    $(window).resize(
        viewport.changed(function() {
            if( viewport.is('xs') ) {
                // ...
            }
        })
    ); 

})(jQuery, ResponsiveBootstrapToolkit);

As of version 2.3.0, you don't need the four <div>elements mentioned below.

从 2.3.0 版本开始,您不需要<div>下面提到的四个元素。



ORIGINAL ANSWER:

原始答案:

I don't think you need any huge script or library for that. It's a fairly simple task.

我认为您不需要任何庞大的脚本或库。这是一个相当简单的任务。

Insert the following elements just before </body>:

在 之前插入以下元素</body>

<div class="device-xs visible-xs"></div>
<div class="device-sm visible-sm"></div>
<div class="device-md visible-md"></div>
<div class="device-lg visible-lg"></div>

These 4 divs allow you check for currently active breakpoint. For an easy JS detection, use the following function:

这 4 个 div 允许您检查当前活动的断点。为了简单的 JS 检测,请使用以下函数:

function isBreakpoint( alias ) {
    return $('.device-' + alias).is(':visible');
}

Now to perform a certain action only on the smallest breakpoint you could use:

现在仅在您可以使用的最小断点上执行特定操作:

if( isBreakpoint('xs') ) {
    $('.someClass').css('property', 'value');
}

Detecting changes after DOM ready is also fairly simple. All you need is a lightweight window resize listener like this one:

在 DOM 就绪后检测更改也相当简单。您只需要一个像这样的轻量级窗口调整大小侦听器:

var waitForFinalEvent = function () {
      var b = {};
      return function (c, d, a) {
        a || (a = "I am a banana!");
        b[a] && clearTimeout(b[a]);
        b[a] = setTimeout(c, d)
      }
    }();

var fullDateString = new Date();

Once you're equipped with it, you can start listening for changes and execute breakpoint-specific functions like so:

一旦你配备了它,你就可以开始监听更改并执行特定于断点的函数,如下所示:

$(window).resize(function () {
    waitForFinalEvent(function(){

        if( isBreakpoint('xs') ) {
            $('.someClass').css('property', 'value');
        }

    }, 300, fullDateString.getTime())
});

回答by mtt

If you don't have specific needs you can just do this:

如果您没有特定需求,您可以这样做:

if ($(window).width() < 768) {
    // do something for small screens
}
else if ($(window).width() >= 768 &&  $(window).width() <= 992) {
    // do something for medium screens
}
else if ($(window).width() > 992 &&  $(window).width() <= 1200) {
    // do something for big screens
}
else  {
    // do something for huge screens
}

Edit: I don't see why you should use another js library when you can do this just with jQuery already included in your Bootstrap project.

编辑:我不明白为什么你应该使用另一个 js 库,当你可以使用已经包含在你的 Bootstrap 项目中的 jQuery 来做到这一点时。

回答by Mousius

Have you taken a look at Response.js? It's designed for this kind of thing. Combine Response.band and Response.resize.

你看过 Response.js 吗?它是为这种事情而设计的。结合 Response.band 和 Response.resize。

http://responsejs.com/

http://responsejs.com/

Response.resize(function() {
    if ( Response.band(1200) )
    {
       // 1200+
    }    
    else if ( Response.band(992) )
    {
        // 992+
    }
    else if ( Response.band(768) )
    {
        // 768+
    }
    else 
    {
        // 0->768
    }
});

回答by srlm

You could use the window size and hard code the breakpoints. Using Angular:

您可以使用窗口大小并对断点进行硬编码。使用角度:

angular
    .module('components.responsiveDetection', [])
    .factory('ResponsiveDetection', function ($window) {
        return {
            getBreakpoint: function () {
                var w = $window.innerWidth;
                if (w < 768) {
                    return 'xs';
                } else if (w < 992) {
                    return 'sm';
                } else if (w < 1200) {
                    return 'md';
                } else {
                    return 'lg';
                }
            }
        };
    });

回答by Farside

Detect responsive breakpoint of Twitter Bootstrap 4.1.x using JavaScript

使用 JavaScript 检测 Twitter Bootstrap 4.1.x 的响应断点

The Bootstrap v.4.0.0(and the latest version Bootstrap 4.1.x) introduced the updated grid options, so the old concept on detection may not directly be applied (see the migration instructions):

引导v.4.0.0(和最新版本的引导4.1.x版)推出的更新网格选项,所以在检测到旧观念可能无法直接被应用(见的迁移说明):

  • Added a new smgrid tier below 768pxfor more granular control. We now have xs, sm, md, lg, and xl;
  • xsgrid classes have been modified to not require the infix.
  • sm在下方添加了一个新的网格层768px以进行更精细的控制。我们现在有xs, sm, md, lg, 和xl;
  • xs网格类已被修改为不需要中缀。

I written the small utility function that respects an updated grid class names and a new grid tier:

我编写了尊重更新的网格类名称和新网格层的小型实用程序函数:

/**
 * Detect the current active responsive breakpoint in Bootstrap
 * @returns {string}
 * @author farside {@link https://stackoverflow.com/users/4354249/farside}
 */
function getResponsiveBreakpoint() {
    var envs = {xs:"d-none", sm:"d-sm-none", md:"d-md-none", lg:"d-lg-none", xl:"d-xl-none"};
    var env = "";

    var $el = $("<div>");
    $el.appendTo($("body"));

    for (var i = Object.keys(envs).length - 1; i >= 0; i--) {
        env = Object.keys(envs)[i];
        $el.addClass(envs[env]);
        if ($el.is(":hidden")) {
            break; // env detected
        }
    }
    $el.remove();
    return env;
};

Detect responsive breakpoint of Bootstrap v4-beta using JavaScript

使用 JavaScript 检测 Bootstrap v4-beta 的响应断点

The Bootstrap v4-alphaand Bootstrap v4-betahad different approach on grid breakpoints, so here's the legacy way of achieving the same:

引导V4-α引导V4-β对电网断点不同的方法,所以这里的达到相同的传统方式:

/**
 * Detect and return the current active responsive breakpoint in Bootstrap
 * @returns {string}
 * @author farside {@link https://stackoverflow.com/users/4354249/farside}
 */
function getResponsiveBreakpoint() {
    var envs = ["xs", "sm", "md", "lg"];
    var env = "";

    var $el = $("<div>");
    $el.appendTo($("body"));

    for (var i = envs.length - 1; i >= 0; i--) {
        env = envs[i];
        $el.addClass("d-" + env + "-none");;
        if ($el.is(":hidden")) {
            break; // env detected
        }
    }
    $el.remove();
    return env;
}

I think it would be useful, as it's easy to integrate to any project. It uses native responsive display classesof the Bootstrap itself.

我认为这很有用,因为它很容易集成到任何项目中。它使用Bootstrap 本身的本机响应显示类

回答by hckr

Here my own simple solution:

这是我自己的简单解决方案:

jQuery:

jQuery:

function getBootstrapBreakpoint(){
    var w = $(document).innerWidth();
    return (w < 768) ? 'xs' : ((w < 992) ? 'sm' : ((w < 1200) ? 'md' : 'lg'));
}

VanillaJS:

香草JS:

function getBootstrapBreakpoint(){
    var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    return (w < 768) ? 'xs' : ((w < 992) ? 'sm' : ((w < 1200) ? 'md' : 'lg'));
}

回答by berkayunal

Using this approach with Response.jsis better. Response.resize triggers on every window resize where crossover will only be triggered if breakpoint is changed

将此方法与Response.js 一起使用会更好。Response.resize 在每个窗口调整大小时触发,其中只有在断点更改时才会触发交叉

Response.create({
    prop : "width",
    breakpoints : [1200, 992, 768, 480, 320, 0]
});

Response.crossover('width', function() {
    if (Response.band(1200)) {
        // 1200+

    } else if (Response.band(992)) {
        // 992+

    } else if (Response.band(768)) {
        // 768+

    } else if (Response.band(480)) {
        //480+

    } else {
        // 0->320

    }
});

Response.ready(function() {
    $(window).trigger('resize');
});

回答by Stone

Building on Maciej Gurban's answer (which is fantastic... if you like this, please just up vote his answer). If you're building a service to query you can return the currently active service with the setup below. This could replace other breakpoint detection libraries entirely (like enquire.js if you put in some events). Note that I've added a container with an ID to the DOM elements to speed up DOM traversal.

以 Maciej Gurban 的回答为基础(这太棒了......如果你喜欢这个,请给他的答案投票)。如果您正在构建一个服务来查询,您可以使用以下设置返回当前活动的服务。这可以完全取代其他断点检测库(例如 enquire.js,如果您放入某些事件)。请注意,我已将带有 ID 的容器添加到 DOM 元素以加快 DOM 遍历。

HTML

HTML

<div id="detect-breakpoints">
    <div class="breakpoint device-xs visible-xs"></div>
    <div class="breakpoint device-sm visible-sm"></div>
    <div class="breakpoint device-md visible-md"></div>
    <div class="breakpoint device-lg visible-lg"></div>
</div>

COFFEESCRIPT (AngularJS, but this is easily convertible)

COFFEESCRIPT(AngularJS,但这很容易转换)

# this simple service allows us to query for the currently active breakpoint of our responsive app
myModule = angular.module('module').factory 'BreakpointService', ($log) ->

  # alias could be: xs, sm, md, lg or any over breakpoint grid prefix from Bootstrap 3
  isBreakpoint: (alias) ->
    return $('#detect-breakpoints .device-' + alias).is(':visible')

  # returns xs, sm, md, or lg
  getBreakpoint: ->
    currentBreakpoint = undefined
    $visibleElement = $('#detect-breakpoints .breakpoint:visible')
    breakpointStringsArray = [['device-xs', 'xs'], ['device-sm', 'sm'], ['device-md', 'md'], ['device-lg', 'lg']]
    # note: _. is the lodash library
    _.each breakpointStringsArray, (breakpoint) ->
      if $visibleElement.hasClass(breakpoint[0])
        currentBreakpoint = breakpoint[1]
    return currentBreakpoint

JAVASCRIPT (AngularJS)

JAVASCRIPT (AngularJS)

var myModule;

myModule = angular.module('modules').factory('BreakpointService', function($log) {
  return {
    isBreakpoint: function(alias) {
      return $('#detect-breakpoints .device-' + alias).is(':visible');
    },
    getBreakpoint: function() {
      var $visibleElement, breakpointStringsArray, currentBreakpoint;
      currentBreakpoint = void 0;
      $visibleElement = $('#detect-breakpoints .breakpoint:visible');
      breakpointStringsArray = [['device-xs', 'xs'], ['device-sm', 'sm'], ['device-md', 'md'], ['device-lg', 'lg']];
      _.each(breakpointStringsArray, function(breakpoint) {
        if ($visibleElement.hasClass(breakpoint[0])) {
          currentBreakpoint = breakpoint[1];
        }
      });
      return currentBreakpoint;
    }
  };
});

回答by effe

You may want to add this to your bootstrap project to check active breakpoint visually

您可能希望将此添加到您的引导项目中以直观地检查活动断点

    <script type='text/javascript'>

        $(document).ready(function () {

            var mode;

            $('<div class="mode-informer label-info" style="z-index:1000;position: fixed;bottom:10px;left:10px">%mode%</div>').appendTo('body');


            var checkMode = function () {

                if ($(window).width() < 768) {
                    return 'xs';
                }
                else if ($(window).width() >= 768 && $(window).width() < 992) {
                    return 'sm';
                }
                else if ($(window).width() >= 992 && $(window).width() < 1200) {
                    return 'md';
                }
                else {
                    return 'lg';
                }
            };

            var compareMode = function () {
                if (mode !== checkMode()) {
                    mode = checkMode();

                    $('.mode-informer').text(mode).animate({
                        bottom: '100'
                    }, 100, function () {
                        $('.mode-informer').animate({bottom: 10}, 100)
                    });
                }
            };

            $(window).on('resize', function () {
                compareMode()
            });

            compareMode();

        });

    </script>

Here is the BOOTPLY

这是BOOTPLY

回答by Matias

There should be no problem with some manual implementation like the one mentioned by @oozic.

像@oozic 提到的那样一些手动实现应该没有问题。

Here are a couple of libs you could take a look at:

这里有几个库你可以看看:

  • Response.js- jQuery plugin - make use of html data attributes and also has a js api.
  • enquire.js- enquire.js is a lightweight, pure JavaScript library for responding to CSS media queries
  • SimpleStateManager- s a javascript state manager for responsive websites. It is built to be light weight, has no dependencies.
  • Response.js- jQuery 插件 - 使用 html 数据属性并且还有一个 js api。
  • enquire.js- enquire.js 是一个轻量级的纯 JavaScript 库,用于响应 CSS 媒体查询
  • SimpleStateManager- 响应式网站的 javascript 状态管理器。它是轻量级的,没有依赖性。

Note that these libs are designed to work independently of bootstrap, foundation, etc. You can configure your own breakpoints and have fun.

请注意,这些库旨在独立于引导程序、基础等工作。您可以配置自己的断点并从中获得乐趣。