IT

JavaScript를 사용하여 Twitter Bootstrap 3의 반응 형 중단 점을 감지하는 방법은 무엇입니까?

lottoking 2020. 6. 24. 07:22
반응형

JavaScript를 사용하여 Twitter Bootstrap 3의 반응 형 중단 점을 감지하는 방법은 무엇입니까?


현재 Twitter Bootstrap 3에는 768px, 992px 및 1200px의 반응 형 중단 점이 있으며 각각 중소형 및 대형 장치를 나타냅니다.

JavaScript를 사용하여 이러한 중단 점을 어떻게 감지 할 수 있습니까?

화면이 변경 될 때 트리거되는 모든 관련 이벤트에 대해 JavaScript로 듣고 싶습니다. 화면이 소형, 중형 또는 대형 장치 용인지 감지 할 수 있습니다.

이미 무슨 일이 있습니까? 당신의 제안은 무엇입니까?


편집 :이 라이브러리는 이제 Bower 및 NPM을 통해 사용할 수 있습니다. 자세한 내용은 github repo를 참조하십시오.

업데이트 된 답변 :

면책 조항 : 나는 저자입니다.

최신 버전 (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);

버전 2.3.0부터는 <div>아래 언급 된 네 가지 요소 가 필요하지 않습니다 .


원래 답변 :

나는 당신이 그것을 위해 거대한 스크립트 나 라이브러리가 필요하다고 생각하지 않습니다. 상당히 간단한 작업입니다.

바로 다음 요소를 삽입하십시오 </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())
});

특정 요구 사항이 없으면 다음과 같이하십시오.

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
}

편집 : Bootstrap 프로젝트에 이미 포함 된 jQuery 로이 작업을 수행 할 수있을 때 왜 다른 js 라이브러리를 사용 해야하는지 모르겠습니다.


Response.js를 보셨습니까? 이런 종류의 것을 위해 설계되었습니다. Response.band와 Response.resize를 결합하십시오.

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

창 크기를 사용하고 중단 점을 하드 코딩 할 수 있습니다. 각도 사용 :

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

JavaScript를 사용하여 Twitter Bootstrap 4.1.x의 반응 형 중단 점 감지

부트 스트랩 v.4.0.0 (최신 버전의 부트 스트랩 전 4.1.x는 ) 업데이트 도입 그리드 옵션을 탐지에 대한 기존의 개념은 직접 (참조 적용되지 않을 수 있으므로, 마이그레이션 지침 ) :

  • 보다 세밀한 제어를 위해 sm아래 768px그리드 계층을 추가했습니다 . 우리는 지금이 xs, sm, md, lg, 그리고 xl;
  • xs 그리드 클래스는 수정이 필요하지 않도록 수정되었습니다.

업데이트 된 그리드 클래스 이름과 새로운 그리드 계층을 고려한 작은 유틸리티 함수를 작성했습니다.

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

JavaScript를 사용하여 Bootstrap v4- 베타의 반응 중단 점 감지

부트 스트랩 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;
}

모든 프로젝트에 쉽게 통합 할 수 있기 때문에 유용 할 것이라고 생각합니다. 부트 스트랩 자체의 기본 응답 디스플레이 클래스사용 합니다.


여기 내 자신의 간단한 해결책 :

jQuery :

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

바닐라 JS :

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

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

@oozic이 언급 한 것과 같은 수동 구현에는 아무런 문제가 없습니다.

다음은 살펴볼 수있는 몇 가지 라이브러리입니다.

  • Response.js -jQuery 플러그인-HTML 데이터 속성을 사용하고 js API도 있습니다.
  • enquire.js -enquire.js는 CSS 미디어 쿼리에 응답하기위한 경량의 순수 JavaScript 라이브러리입니다.
  • SimpleStateManager- 반응 형 웹 사이트를위한 자바 스크립트 상태 관리자. 가벼운 무게로 만들어졌으며 의존성이 없습니다.

이 라이브러리는 부트 스트랩, 기초 등 독립적으로 작동하도록 설계되었습니다. 고유 한 중단 점을 구성하고 재미있게 사용할 수 있습니다.


부트 스트랩 프로젝트에 이것을 추가하여 활성 중단 점을 시각적으로 확인할 수 있습니다

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

여기 BOOTPLY입니다


Maciej Gurban의 답변을 바탕으로 (환상적입니다 ... 좋으면 그의 답변에 투표하십시오). 쿼리 할 서비스를 구축하는 경우 아래 설정으로 현재 활성화 된 서비스를 반환 할 수 있습니다. 이것은 다른 중단 점 감지 라이브러리를 완전히 대체 할 수 있습니다 (일부 이벤트를 입력하면 enquire.js와 같은). DOM 탐색 속도를 높이기 위해 ID가있는 컨테이너를 DOM 요소에 추가했습니다.

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이지만 쉽게 변환 가능)

# 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

자바 스크립트 (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;
    }
  };
});

$ (document) .width ()를 사용하는 대신이 정보를 제공하는 CSS 규칙을 설정해야합니다.

방금 정확한 기사를 썼습니다. 여기를 참조하십시오 : http://www.xurei-design.be/2013/10/how-to-accurately-detect-responsive-breakpoints/


왜 jQuery를 사용하여 부트 스트랩 컨테이너 클래스의 현재 CSS 너비를 감지하지 않습니까?

즉 ..

if( parseInt($('#container').css('width')) > 1200 ){
  // do something for desktop screens
}

누군가가 브라우저 창의 크기를 조정하는 경우 $ (window) .resize ()를 사용하여 레이아웃이 "침대를 더럽 히지"않도록 할 수 있습니다.


각 페이지에 아래를 여러 번 삽입하는 대신 ...

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

JavaScript를 사용하여 모든 페이지에 동적으로 삽입하십시오 (Bootstrap 3에서 .visible-*-block다음 같이 작동하도록 업데이트했습니다 .

// Make it easy to detect screen sizes
var bootstrapSizes = ["xs", "sm", "md", "lg"];
for (var i = 0; i < bootstrapSizes.length; i++) {
    $("<div />", {
        class: 'device-' + bootstrapSizes[i] + ' visible-' + bootstrapSizes[i] + '-block'
    }).appendTo("body");
}

언급 할만한 평판이 충분하지 않지만 Maciej Gurban의 ResponsiveToolKit을 사용할 때 "인식되지 않는"문제가있는 사람들에게는 Maciej가 실제로 툴킷을 맨 아래에서 참조한다는 것을 알 때까지 그 오류가 발생했습니다. 그의 CodePen의 페이지

나는 그것을 시도하고 갑자기 작동했습니다! 따라서 ResponsiveToolkit을 사용하지만 페이지 하단에 링크를 넣으십시오.

왜 차이가 나는지 모르겠지만 그렇지 않습니다.


자바 스크립트에 뷰포트 크기를 입력 하지 않고 현재 뷰포트를 감지하는 다른 방법이 있습니다.

https://gist.github.com/steveh80/288a9a8bd4c3de16d799 : CSS 및 자바 스크립트 스 니펫을 참조하십시오

해당 스 니펫을 CSS 및 자바 스크립트 파일에 추가 한 후 다음과 같이 현재 뷰포트를 감지 할 수 있습니다.

viewport.is('xs') // returns boolean

뷰포트 범위를 감지하려면 다음과 같이 사용하십시오.

viewport.isEqualOrGreaterThan('sm') // returns true for sm, md and lg

.container클래스 의 부트 스트랩 CSS는 다음과 같습니다.

.container {
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
@media (min-width: 768px) {
    .container {
        width: 750px;
    }
}
@media (min-width: 992px) {
    .container {
        width: 970px;
    }
}
@media (min-width: 1200px) {
    .container {
        width: 1170px;
    }
}

따라서 이는 의지 jQuery('.container').css('width')의 결점없이 중단 점을 감지하는 데 안전하게 의존 할 수 있음을 의미 합니다 jQuery(window).width().

다음과 같은 함수를 작성할 수 있습니다.

function detectBreakpoint() {
    // Let's ensure we have at least 1 container in our pages.
    if (jQuery('.container').length == 0) {
        jQuery('body').append('<div class="container"></div>');
    }

    var cssWidth = jQuery('.container').css('width');

    if (cssWidth === '1170px') return 'lg';
    else if (cssWidth === '970px') return 'md';
    else if (cssWidth === '750px') return 'sm';

    return 'xs';
}

그런 다음 테스트하십시오.

jQuery(document).ready(function() {
    jQuery(window).resize(function() {
        jQuery('p').html('current breakpoint is: ' + detectBreakpoint());
    });

    detectBreakpoint();
});

CSS :beforecontent속성을 사용하여 중단 점 상태를 인쇄 <span id="breakpoint-js">하므로 JavaScript는이 데이터를 읽어 함수 내에서 사용할 변수로 설정하기 만하면됩니다.

(스 니펫을 실행하여 예제를보십시오)

참고 : 브라우저 상단 모서리에 빨간색 플래그로 사용하기 위해 몇 줄의 CSS를 추가했습니다 <span>. display:none;물건을 공개하기 전에 다시 전환하십시오 .

// initialize it with jquery when DOM is ready
$(document).on('ready', function() {
    getBootstrapBreakpoint();
});

// get bootstrap grid breakpoints
var theBreakpoint = 'xs'; // bootstrap336 default = mobile first
function getBootstrapBreakpoint(){
   theBreakpoint = window.getComputedStyle(document.querySelector('#breakpoint-js'),':before').getPropertyValue('content').replace(/['"]+/g, '');
   console.log('bootstrap grid breakpoint = ' + theBreakpoint);
}
#breakpoint-js {
  /* display: none; //comment this while developping. Switch back to display:NONE before commit */
  /* optional red flag layout */
  position: fixed;
  z-index: 999;
  top: 0;
  left: 0;
  color: white;
  padding: 5px 10px;
  background-color: red;
  opacity: .7;
  /* end of optional red flag layout */
}
#breakpoint-js:before {
  content: 'xs'; /* default = mobile first */
}
@media screen and (min-width: 768px) {
  #breakpoint-js:before {
    content: 'sm';
  }
}
@media screen and (min-width: 992px) {
  #breakpoint-js:before {
    content: 'md';
  }
}
@media screen and (min-width: 1200px) {
  #breakpoint-js:before {
    content: 'lg';
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<div class="container">
  <span id="breakpoint-js"></span>
  <div class="page-header">
    <h1>Bootstrap grid examples</h1>
    <p class="lead">Basic grid layouts to get you familiar with building within the Bootstrap grid system.</p>
  </div>
</div>


Twitter Bootstrap 화면 크기 감지를 위해 기본 jQuery 메소드를 만들었습니다. 여기 있습니다 :

// Screen size ID will be stored in this variable (global var for JS)
var CurrentBootstrapScreenSize = 'unknown';

$(document).ready(function () {

    // <div> objects for all screen sizes required for screen size detection.
    // These <div> is hidden for users eyes.
    var currentScreenSizeDetectorObjects = $('<div>').css({
            'position':'absolute',
            'top':'-200px'
        }).addClass('current-screen-size').append([
            $('<div>').addClass('device-xs visible-xs').html('&nbsp;'),
            $('<div>').addClass('device-sm visible-sm').html('&nbsp;'),
            $('<div>').addClass('device-md visible-md').html('&nbsp;'),
            $('<div>').addClass('device-lg visible-lg').html('&nbsp;')
        ]);

    // Attach <div> objects to <body>
    $('body').prepend(currentScreenSizeDetectorObjects);

    // Core method for detector
    function currentScreenSizeDetectorMethod() {
        $(currentScreenSizeDetectorObjects).find('div').each(function() {
            var className = $(this).attr('class');
            if($(this).is(':visible')) {
                if(String(className).match(/device-xs/)) CurrentBootstrapScreenSize = 'xs';
                else if(String(className).match(/device-sm/)) CurrentBootstrapScreenSize = 'sm';
                else if(String(className).match(/device-md/)) CurrentBootstrapScreenSize = 'md';
                else if(String(className).match(/device-lg/)) CurrentBootstrapScreenSize = 'lg';
                else CurrentBootstrapScreenSize = 'unknown';
            };
        })
        console.log('Current Bootstrap screen size is: '+CurrentBootstrapScreenSize);
        $('.CurrentBootstrapScreenSize').first().html('Bootstrap current screen size: <b>' + CurrentBootstrapScreenSize + '</b>' );
    }

    // Bind screen size and orientation change
    $(window).bind("resize orientationchange", function() {
        // Execute screen detection
        currentScreenSizeDetectorMethod();
    });

    // Execute screen detection on page initialize
    currentScreenSizeDetectorMethod();

});

JSFillde : https://jsfiddle.net/pstepniewski/7dz6ubus/

전체 화면 예 : JSFillde : https://jsfiddle.net/pstepniewski/7dz6ubus/embedded/result/


이것에 관심이있는 사람은 TypeScript와 Observables를 사용하여 CSS 중단 점을 기반으로 중단 점 감지를 작성했습니다. 유형을 제거하면 ES6을 만드는 것이 그리 어렵지 않습니다. 내 예에서는 Sass를 사용하지만 이것을 제거하는 것도 쉽습니다.

여기 내 JSFiddle이 있습니다 : https://jsfiddle.net/StefanJelner/dorj184g/

HTML :

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.7/Rx.min.js"></script>
<div id="result"></div>

SCSS :

body::before {
  content: 'xs';
  display: none;

  @media screen and (min-width: 480px) {
    content: 's';
  }

  @media screen and (min-width: 768px) {
    content: 'm';
  }

  @media screen and (min-width: 1024px) {
    content: 'l';
  }

  @media screen and (min-width: 1280px) {
    content: 'xl';
  }
}

TypeScript :

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

class BreakpointChangeService {
    private breakpointChange$: BehaviorSubject<string>;

    constructor(): BehaviorSubject<string> {
        // initialize BehaviorSubject with the current content of the ::before pseudo element
        this.breakpointChange$ = new Rx.BehaviorSubject(this.getBreakpoint());

        // observe the window resize event, throttle it and combine it with the BehaviorSubject
        Rx.Observable
            .fromEvent(window, 'resize')
            .throttleTime(0, Rx.Scheduler.animationFrame)
            .withLatestFrom(this.breakpointChange$)
            .subscribe(this.update.bind(this))
        ;

        return this.breakpointChange$;
    }

    // method to get the content of the ::before pseudo element
    private getBreakpoint(): string {
        // see https://www.lullabot.com/articles/importing-css-breakpoints-into-javascript
        return window.getComputedStyle(document.body, ':before').getPropertyValue('content').replace(/[\"\']/g, '');
    }

    private update(_, recent): void {
        var current = this.getBreakpoint();
        if(recent !== current) { this.breakpointChange$.next(current); }
    }
}

// if the breakpoint changes, react on it
var $result = document.getElementById('result');
new BreakpointChangeService().subscribe(breakpoint => {
    $result.innerHTML = Date.now()+': '+breakpoint;
});

나는 이것이 누군가를 돕기를 바랍니다.


jQuery가 포함 된 Bootstrap4, 간소화 된 솔루션

<div class="device-sm d-sm-none"></div>
<div class="device-md d-md-none"></div>
<div class="device-lg d-lg-none"></div>
<div class="device-xl d-xl-none"></div>
<script>
var size = $('.device-xl').is(':hidden') ? 'xl' : ($('.device-lg').is(':hidden') ? 'lg'
    : ($('.device-md').is(':hidden') ? 'md': ($('.device-sm').is(':hidden') ? 'sm' : 'xs')));
alert(size);
</script>

나는 주어진 대답에 정말로 만족하지 않았는데, 이는 나에게 사용하기가 지나치게 복잡해 보이므로 내 자신의 해결책을 썼습니다. 그러나 당분간 이것은 밑줄 / lodash에 의존하여 작동합니다.

https://github.com/LeShrimp/GridSizeEvents

다음과 같이 사용할 수 있습니다.

GridSizeEvents.addListener(function (newSize, oldSize) {
    // Will output eg. "xs -> sm"
    console.log(oldSize + ' -> ' + newSize);
});

중단 점은 768px, 992px 및 1200px로 하드 코딩되어 있기 때문에 이것은 Bootstrap 3 용 박스에서 작동합니다. 다른 버전의 경우 코드를 쉽게 적용 할 수 있습니다.

내부적으로 이것은 matchMedia ()를 사용 하므로 Bootstrap과 동기화 된 결과를 보장해야합니다.


어쩌면 그것은 당신 중 일부를 도울 것입니다, 그러나 당신이보고 있는 현재 Bootstrap v4 중단 점 을 감지하는 데 도움이되는 플러그인 이 있습니다 : https://www.npmjs.com/package/bs-breakpoints

사용하기 간단 함 (jQuery와 함께 또는없이 사용 가능) :

$(document).ready(function() {
  bsBreakpoints.init()
  console.warn(bsBreakpoint.getCurrentBreakpoint())

  $(window).on('new.bs.breakpoint', function (event) {
    console.warn(event.breakpoint)
  })
})

누구나 사용하기 위해 knockout.js , 좀 싶어 knockout.js을 관찰 특성 중단 점을 칠 때 말해 것입니다. CSS 스타일 미디어 쿼리에 Modernizr의 지원 을 사용 하여 숫자가 부트 스트랩 정의와 일치하고 modernizr의 호환성 이점을 얻도록 선택했습니다. 내 녹아웃 뷰 모델은 다음과 같습니다.

var viewModel = function() {
    // depends on jquery, Modernizr
    var self = this;
    self.widthXsOrLess = ko.observable();
    self.widthSmOrLess = ko.observable();
    self.widthMdOrLess = ko.observable();
    var setWindowSizeVars = function() {
        self.widthXsOrLess(!Modernizr.mq('(min-width: 768px)'));
        self.widthSmOrLess(!Modernizr.mq('(min-width: 992px)'));
        self.widthMdOrLess(!Modernizr.mq('(min-width: 1200px)'));
    };
    $(window).resize(setWindowSizeVars);
    setWindowSizeVars();
};

다음은 그것을 감지하는 좋은 방법입니다 (아마 웃기는하지만 작동합니다). 필요한 요소를 사용할 수 있으므로 코드가 명확합니다.

예 : CSS :

@media (max-width: 768px) {
    #someElement
    {
         background: pink
    }
}

jQuery에 의한 문서에서 :

if($('#someElement').css('background') == 'pink')
{
    doWhatYouNeed();
}

물론 CSS 속성은 임의입니다.


부트 스트랩 4가 곧 나올 것이기 때문에 지원하는 기능을 공유하고 (xl은 이제 일입니다) 최소한의 jQuery를 수행하여 작업을 완료 할 것이라고 생각했습니다.

/**
 * Get the Bootstrap device size
 * @returns {string|boolean} xs|sm|md|lg|xl on success, otherwise false if Bootstrap is not working or installed
 */
function findBootstrapEnvironment() {
    var environments = ['xs', 'sm', 'md', 'lg', 'xl'];
    var $el = $('<span />');
    $el.appendTo($('body'));
    for (var i = environments.length - 1; i >= 0; i--) {
        var env = environments[i];
        $el.addClass('hidden-'+env);
        if ($el.is(':hidden')) {
            $el.remove();
            return env;
        }
    }
    $el.remove();
    return false;
}

부트 스트랩 4

setResponsiveDivs();

function setResponsiveDivs() {
    var data = [
        {id: 'visible-xs', class: 'd-block d-sm-none'},
        {id: 'visible-sm', class: 'd-none d-sm-block d-md-none'},
        {id: 'visible-md', class: 'd-none d-md-block d-lg-none'},
        {id: 'visible-lg', class: 'd-none d-lg-block d-xl-none'},
        {id: 'visible-xl', class: 'd-none d-xl-block'}
    ];

    for (var i = 0; i < data.length; i++) {
        var el = document.createElement("div");
        el.setAttribute('id', data[i].id);
        el.setAttribute('class', data[i].class);
        document.getElementsByTagName('body')[0].appendChild(el);
    }
}

function isVisible(type) {
    return window.getComputedStyle(document.getElementById('visible-' + type), null).getPropertyValue('display') === 'block';
}

// then, at some point
window.onresize = function() {
    console.log(isVisible('xs') === true ? 'xs' : '');
    console.log(isVisible('sm') === true ? 'sm' : '');
    console.log(isVisible('md') === true ? 'md' : '');
    console.log(isVisible('lg') === true ? 'lg' : '');
    console.log(isVisible('xl') === true ? 'xl' : '');
};

또는 축소

function setResponsiveDivs(){for(var e=[{id:"visible-xs","class":"d-block d-sm-none"},{id:"visible-sm","class":"d-none d-sm-block d-md-none"},{id:"visible-md","class":"d-none d-md-block d-lg-none"},{id:"visible-lg","class":"d-none d-lg-block d-xl-none"},{id:"visible-xl","class":"d-none d-xl-block"}],s=0;s<e.length;s++){var l=document.createElement("div");l.setAttribute("id",e[s].id),l.setAttribute("class",e[s]["class"]),document.getElementsByTagName("body")[0].appendChild(l)}}function isVisible(e){return"block"===window.getComputedStyle(document.getElementById("visible-"+e),null).getPropertyValue("display")}setResponsiveDivs();


Knockout 을 사용 하는 경우 다음 사용자 정의 바인딩을 사용하여 현재 뷰포트 중단 점 (xs, sm, md 또는 lg)을 모델의 Observable에 바인딩 할 수 있습니다. 바인딩 ...

  • id가있는 div의 클래스로 4 divs감싸고 존재하지 않는 경우 본문에 추가합니다 (따라서이 div를 복제하지 않고이 바인딩을 재사용 할 수 있습니다)visible-??detect-viewport
  • 표시되는 div를 쿼리하여 현재 뷰포트 중단 점을 바운드 관찰 가능으로 설정합니다.
  • 창의 크기를 조정할 때 현재 뷰포트 중단 점을 업데이트합니다

ko.bindingHandlers['viewport'] = {
    init: function(element, valueAccessor) {
        if (!document.getElementById('detect-viewport')) {
            let detectViewportWrapper = document.createElement('div');
            detectViewportWrapper.id = 'detect-viewport';
            
            ["xs", "sm", "md", "lg"].forEach(function(breakpoint) {
                let breakpointDiv = document.createElement('div');
                breakpointDiv.className = 'visible-' + breakpoint;
                detectViewportWrapper.appendChild(breakpointDiv);
            });

            document.body.appendChild(detectViewportWrapper);
        }

        let setCurrentBreakpoint = function() {
            valueAccessor()($('#detect-viewport div:visible')[0].className.substring('visible-'.length));
        }
      
        $(window).resize(setCurrentBreakpoint);
        setCurrentBreakpoint();
    }
};

ko.applyBindings({
  currentViewPort: ko.observable()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div data-bind="viewport: currentViewPort"></div>
<div>    
    Current viewport breakpoint: <strong data-bind="text: currentViewPort"></strong>
</div>
<div>
    (Click the <em>full page</em> link of this snippet to test the binding with different window sizes)
</div>


OP 이후 오랜 시간이 지났지 만 여기에 Bootstrap 3을 사용하는 솔루션이 있습니다. 사용 사례에서는 행만 타겟팅했지만 컨테이너에도 동일하게 적용 할 수 있습니다.

.row를 원하는대로 변경하십시오.

jQuery(document).ready(function ($) {

    var alterClass = function () {

        var ww = document.body.clientWidth;

        if (ww < 768) {

            $('.row').addClass('is-xs').removeClass('is-sm').removeClass('is-lg').removeClass('is-md');

        } else if (ww >= 768 && ww < 992) {

            $('.row').addClass('is-sm').removeClass('is-xs').removeClass('is-lg').removeClass('is-md');

        } else if (ww >= 992 && ww < 1200) {

            $('.row').addClass('is-md').removeClass('is-xs').removeClass('is-lg').removeClass('is-sm');

        } else if (ww >= 1200) {

            $('.row').addClass('is-lg').removeClass('is-md').removeClass('is-sm').removeClass('is-xs');

        };
    };

    // Make Changes when the window is resized
    $(window).resize(function () {
        alterClass();
    });

    // Fire when the page first loads
    alterClass();
});

참고 URL : https://stackoverflow.com/questions/18575582/how-to-detect-responsive-breakpoints-of-twitter-bootstrap-3-using-javascript

반응형