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

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

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

How can I detect these breakpoints using 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.

Is there something already done? What are your suggestions?

ベストアンサー1

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

UPDATED ANSWER:

免責事項: 私は著者です。

最新バージョン (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);

<div>バージョン 2.3.0 以降では、以下の4 つの要素は必要ありません。


元の回答:

そのために巨大なスクリプトやライブラリは必要ないと思います。かなり簡単な作業です。

の直前に次の要素を挿入します</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>

これら 4 つの div を使用すると、現在アクティブなブレークポイントを確認できます。簡単な JS 検出を行うには、次の関数を使用します。

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

最小のブレークポイントでのみ特定のアクションを実行するには、次のようにします。

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

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();

これを装備すると、変更をリッスンし、次のようにブレークポイント固有の関数を実行できるようになります。

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

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

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

おすすめ記事