Javascript 如何使用 Twitter Bootstrap API 检测您正在使用哪个设备视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14441456/
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-08-24 16:46:47  来源:igfitidea点击:

How to detect which device view you're on using Twitter Bootstrap API?

javascripttwitter-bootstrapdevice-detection

提问by James Howell

I have just started to play around with Twitter Bootstrap API for a project I have coming up. The main nav contains 3 main elements:

我刚刚开始为我即将推出的项目使用 Twitter Bootstrap API。主导航包含 3 个主要元素:

  • site nav
  • social links nav
  • search the site form
  • 网站导航
  • 社交链接导航
  • 搜索网站表格

I am using the collapse plugin to collapse the site nav and search form when viewing the site on mobile devices. The mobile view has 2 buttons which when clicked toggle the search form or main nav on/off.

在移动设备上查看站点时,我正在使用折叠插件折叠站点导航和搜索表单。移动视图有 2 个按钮,单击这些按钮可以打开/关闭搜索表单或主导航。

However if I toggle off the search form and then resize my browser to desktop view the search form is still hidden in this view?

但是,如果我关闭搜索表单,然后将浏览器的大小调整为桌面视图,搜索表单是否仍隐藏在此视图中?

I have read about using classes such as visible-mobile etc but these seem to clash with the collapse plugin. I also realise I could probably write my own CSS hacks to fix this but thought I'd ask if there was an easier solution.

我已经阅读了关于使用诸如visible-mobile 等类的信息,但这些似乎与折叠插件发生冲突。我也意识到我可能会编写自己的 CSS hack 来解决这个问题,但我想我会问是否有更简单的解决方案。

Bootstrap has events for show, shown, hide and hidden so I thought maybe I could write some custom JS which would show or hide these items in each particular device view. However I didn't know how to detect which device I'm using at the time.

Bootstrap 具有用于显示、显示、隐藏和隐藏的事件,所以我想也许我可以编写一些自定义 JS 来在每个特定设备视图中显示或隐藏这些项目。但是,我当时不知道如何检测我正在使用的设备。

Thoughts?

想法?

Thanks in advance

提前致谢

回答by rmobis

If you want to know what environment you're on, try using Bootstrap's own CSS classes. Create an element, add it to the page, apply its helper classes and check if it's hidden to determine if that's the current environment. The following function does just that:

如果您想知道您在什么环境中,请尝试使用 Bootstrap 自己的 CSS 类。创建一个元素,将其添加到页面,应用其辅助类并检查它是否隐藏以确定它是否是当前环境。下面的函数就是这样做的:

Bootstrap 4

引导程序 4

function findBootstrapEnvironment() {
    let envs = ['xs', 'sm', 'md', 'lg', 'xl'];

    let el = document.createElement('div');
    document.body.appendChild(el);

    let curEnv = envs.shift();

    for (let env of envs.reverse()) {
        el.classList.add(`d-${env}-none`);

        if (window.getComputedStyle(el).display === 'none') {
            curEnv = env;
            break;
        }
    }

    document.body.removeChild(el);
    return curEnv;
}


Bootstrap 3

引导程序 3

function findBootstrapEnvironment() {
    var envs = ['xs', 'sm', 'md', 'lg'];

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

    for (var i = envs.length - 1; i >= 0; i--) {
        var env = envs[i];

        $el.addClass('hidden-'+env);
        if ($el.is(':hidden')) {
            $el.remove();
            return env;
        }
    }
}


Bootstrap 2

引导程序 2

function findBootstrapEnvironment() {
    var envs = ['phone', 'tablet', 'desktop'];

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

    for (var i = envs.length - 1; i >= 0; i--) {
        var env = envs[i];

        $el.addClass('hidden-'+env);
        if ($el.is(':hidden')) {
            $el.remove();
            return env;
        }
    }
}

回答by Alastair McCormack

Building on @Raphael_ and @user568109 's answers, in Bootstrap 3, Responsive is now built in.

基于@Raphael_ 和@user568109 的答案,在 Bootstrap 3 中,现在内置了响应式。

To detect device type in Javascript, create an object that is only displayed on your required device using Bootstrap's Responsive classes. Then check its :hiddenproperty.

要在 Javascript 中检测设备类型,请使用 Bootstrap 的响应类创建一个仅显示在所需设备上的对象。然后检查它的:hidden属性。

Example:

例子:

  1. Create a <div>panel with no content that would be shown on anything bigger that an eXtra Small device (thanks to @Mario Awad) :

    <div id="desktopTest" class="hidden-xs"></div>
    

    or, to exclude specific devices:

    <div id="desktopTest" class="visible-sm visible-md visible-lg"></div>
    
  2. Check value of #desktopTest:

    if ($('#desktopTest').is(':hidden')) {
        // device is == eXtra Small
    } else {
        // device is >= SMaller 
    }
    
  1. 创建一个<div>没有内容的面板,该面板将显示在比 eXtra Small 设备更大的任何设备上(感谢 @Mario Awad):

    <div id="desktopTest" class="hidden-xs"></div>
    

    或者,排除特定设备:

    <div id="desktopTest" class="visible-sm visible-md visible-lg"></div>
    
  2. 检查 的值#desktopTest

    if ($('#desktopTest').is(':hidden')) {
        // device is == eXtra Small
    } else {
        // device is >= SMaller 
    }
    

回答by Kar.ma

Original answer:
Based on @Alastair McCormack answer, I suggest you to use this code

原始答案
基于@Alastair McCormack 的答案,我建议您使用此代码

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

Just add it in the end of your container div, you will get a simple dynamic information about current view.

只需将其添加到容器 div 的末尾,您将获得有关当前视图的简单动态信息。

Update (2019-03-03):
Previous code is not compatible with Bootstrap 4, since all hidden-*and visible-*classes have been removed. Here you have the new code you can use, compatible with both Bootstrap 3 and Bootstrap 4 versions (some credits goes to this SO answer):

更新 (2019-03-03)
以前的代码与 Bootstrap 4 不兼容,因为所有hidden-*visible-*类都已被删除。在这里,您可以使用新代码,与 Bootstrap 3 和 Bootstrap 4 版本兼容(一些功劳归于这个 SO 答案):

<div class="visible-xs hidden-sm hidden-md hidden-lg hidden-xl d-block d-sm-none">xs</div>
<div class="hidden-xs visible-sm hidden-md hidden-lg hidden-xl d-none d-sm-block d-md-none">sm</div>
<div class="hidden-xs hidden-sm visible-md hidden-lg hidden-xl d-none d-md-block d-lg-none">md</div>
<div class="hidden-xs hidden-sm hidden-md visible-lg hidden-xl d-none d-lg-block d-xl-none">lg</div>
<div class="hidden-xs hidden-sm hidden-md hidden-lg visible-xl d-none d-xl-block">xl</div>

You can test it with this fiddle.

你可以用这个 fiddle测试它。

Please note that I included hidden-xland visible-xltoo, but I believe they are not really used by any Bootstrap version.

请注意,我包括hidden-xlvisible-xl过,但我相信他们是不是真的被任何引导版本。

回答by Farside

I originally posted answer here, the solution for Bootstrap v.4.x.

我最初在这里发布了答案Bootstrap v.4.x的解决方案。

JS breakpoint detection for Twitter Bootstrap 4.1.x

Twitter Bootstrap 4.1.x 的 JS 断点检测

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;
};

JS breakpoint detection for Bootstrap v4-beta

Bootstrap v4-beta 的 JS 断点检测

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

最新的Bootstrap v4-alphaBootstrap v4-beta在网格断点上有不同的方法,所以这里是实现相同的传统方法:

/**
 * 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 Maciej Gurban

My answer is using similar mechanism like the one presented by @Raphael_ however, you can do a little bit more with it. Please refer to this answerfor details and project's github repositoryfor the most updated version.

我的答案是使用类似于@Raphael_ 提出的机制,但是,您可以用它做更多的事情。有关详细信息和最新版本的项目github 存储库,请参阅此答案

Example of breakpoint detection:

断点检测示例:

if ( viewport.is('xs') ) {
  // do stuff in the lowest resolution
}

Executing code on window resize (without it happening multiple times within a span of milliseconds):

在调整窗口大小时执行代码(在几毫秒内不会多次发生):

$(window).bind('resize', function() {
    viewport.changed(function() {

      // do some other stuff!

    })
});

回答by Skonesam

Niche case, but you can apply @Kar.ma's to a Mediawiki with Chameleon (bootstrap skin) installed. Pass the "results" of the DIV as a template argument, then test against that within the template.

利基案例,但您可以将@Kar.ma 应用到安装了 Chameleon(引导程序皮肤)的 Mediawiki。将 DIV 的“结果”作为模板参数传递,然后针对模板中的结果进行测试。

回答by Puneet Thapliyal

Combining the answers from above, this one works for me:

结合上面的答案,这个对我有用:

function findBootstrapDeviceSize() {
  var dsize = ['lg', 'md', 'sm', 'xs'];
  for (var i = dsize.length - 1; i >= 0; i--) {

    // Need to add &nbsp; for Chrome. Works fine in Firefox/Safari/Opera without it.
    // Chrome seem to have an issue with empty div's
    $el = $('<div id="sizeTest" class="hidden-'+dsize[i]+'">&nbsp;</div>');
    $el.appendTo($('body'));

    if ($el.is(':hidden')) {
      $el.remove();
      return dsize[i];
    }
  }

  return 'unknown';
}