Programing

Twitter 부트 스트랩을 사용하여 요소를 숨기고 jQuery를 사용하여 표시하는 방법은 무엇입니까?

lottogame 2020. 4. 24. 08:02
반응형

Twitter 부트 스트랩을 사용하여 요소를 숨기고 jQuery를 사용하여 표시하는 방법은 무엇입니까?


이와 같은 HTML 요소를 생성한다고 가정 해 보겠습니다.

<div id="my-div" class="hidden">Hello, TB3</div>
<div id="my-div" class="hide">Hello, TB4</div>
<div id="my-div" class="d-none">Hello, TB4</div>

jQuery / Javascript에서 해당 HTML 요소를 표시하고 숨기는 방법은 무엇입니까?

자바 스크립트 :

$(function(){
  $("#my-div").show();
});

결과 : (이 중 하나와 함께).

위의 요소를 숨기고 싶습니다.

부트 스트랩을 사용하여 요소를 숨기고 jQuery를 사용하여 표시하는 가장 간단한 방법은 무엇입니까?


정답

부트 스트랩 4.x

Bootstrap 4.x는 새로운 .d-none클래스를 사용합니다 . 을 사용 하는 대신 .hidden또는 .hideBootstrap 4.x를 사용하는 경우을 사용하십시오 .d-none.

<div id="myId" class="d-none">Foobar</div>
  • 그것을 보여주기 위해 : $("#myId").removeClass('d-none');
  • 숨기려면 $("#myId").addClass('d-none');
  • 토글하려면 : $("#myId").toggleClass('d-none');

(Fangming의 의견에 감사드립니다)

부트 스트랩 3.x

먼저 사용하지 마십시오 .hide! 사용하십시오 .hidden. 다른 사람들이 말했듯 .hide이 더 이상 사용되지 않습니다.

.hide를 사용할 수 있지만 화면 판독기에 영향을주는 것은 아니며 v3.0.1부터는 사용되지 않습니다.

둘째, jQuery의 .toggleClass () , .addClass ().removeClass ()를 사용하십시오.

<div id="myId" class="hidden">Foobar</div>
  • 그것을 보여주기 위해 : $("#myId").removeClass('hidden');
  • 숨기려면 $("#myId").addClass('hidden');
  • 토글하려면 : $("#myId").toggleClass('hidden');

CSS 클래스를 사용하지 마십시오 .show. 유스 케이스가 매우 작습니다. 의 정의는 show, hiddeninvisible에있는 문서 .

// Classes
.show {
  display: block !important;
}
.hidden {
  display: none !important;
  visibility: hidden !important;
}
.invisible {
  visibility: hidden;
}

간단히:

$(function(){
  $("#my-div").removeClass('hide');
});

또는 어떻게 든 수업을 계속 원한다면 :

$(function(){
  $("#my-div").css('display', 'block !important');
});

이 솔루션은 더 이상 사용되지 않습니다. 가장 많이 투표 된 솔루션을 사용하십시오.

hide클래스는 페이지로드시 컨텐츠를 숨기는 데 유용합니다.

이것에 대한 나의 해결책은 초기화하는 동안 jquery의 숨기기로 전환하십시오.

$('.targets').hide().removeClass('hide');

이어서 show()하고 hide()정상적으로 작동한다.


.hidden 대신 bootstrap .collapse를 사용하십시오.

나중에 JQuery에서 .show () 또는 .hide ()를 사용하여 조작 할 수 있습니다.


이 성가심을 해결하는 또 다른 방법은 다음과 같이 규칙 끝에! important를 설정하지 않는 자체 CSS 클래스를 만드는 것입니다.

.hideMe {
    display: none;
}

다음과 같이 사용됩니다.

<div id="header-mask" class="hideMe"></div>

이제 jQuery 숨기기가 작동합니다.

$('#header-mask').show();

@ dustin-graham이 설명한 방법은 내가하는 방법입니다. 또한 부트 스트랩 3은 getbootstrap 의 설명서에 따라 "숨기기"대신 "숨김"을 사용 합니다. 그래서 나는 이런 식으로 할 것입니다 :

$(document).ready(function() {
    $('.hide').hide().removeClass('hide');
    $('.hidden').hide().removeClass('hidden');
});

그런 다음 jQuery show()hide()메소드를 사용할 때마다 충돌이 없습니다.


다음과 같이 요소를 시작하십시오.

<div id='foo' style="display: none"></div>

그런 다음 표시하려는 이벤트를 다음과 같이 사용하십시오.

$('#foo').show();

가장 간단한 방법은 믿습니다.


HTML :

<div id="my-div" class="hide">Hello, TB3</div>

자바 스크립트 :

$(function(){
    //If the HIDE class exists then remove it, But first hide DIV
    if ( $("#my-div").hasClass( 'hide' ) ) $("#my-div").hide().removeClass('hide');

    //Now, you can use any of these functions to display
    $("#my-div").show();
    //$("#my-div").fadeIn();
    //$("#my-div").toggle();
});

toggleClass를 사용하고 싶습니다.

var switch = true; //it can be an JSON value ...
$("#my-div").toggleClass('hide', switch);

$(function(){

$("#my-div").toggle();

$("#my-div").click(function(){$("#my-div").toggle()})

})

// #my-div .hidenor 를 설정할 필요가 없으며 !important이벤트 함수에서 토글을 붙여 넣거나 반복하기 만하면됩니다.


최근 2.3에서 3.1로 업그레이드 할 때이 문제가 발생했습니다. 페이지 템플릿의 요소를 숨기고 있기 때문에 jQuery 애니메이션 ( slideDown )이 중단되었습니다 . 우리는 이제 추악한 중요한 규칙을 따르는 이름 공간 버전의 Bootstrap 클래스를 만드는 경로를 밟았습니다 .

.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...

Razz의 답변은 자신이 한 일을 기꺼이 다시 쓰려고한다면 좋습니다.

같은 문제에 처해 다음과 같이 해결했습니다.

/**
 * The problem: https://github.com/twbs/bootstrap/issues/9881
 * 
 * This script enhances jQuery's methods: show and hide dynamically.
 * If the element was hidden by bootstrap's css class 'hide', remove it first.
 * Do similar in overriding the method 'hide'.
 */
!function($) {
    "use strict";

    var oldShowHide = {'show': $.fn.show, 'hide': $.fn.hide};
    $.fn.extend({
        show: function() {
            this.each(function(index) {
                var $element = $(this);
                if ($element.hasClass('hide')) {
                    $element.removeClass('hide');
                }
            });
            return oldShowHide.show.call(this);
        },
        hide: function() {
            this.each(function(index) {
                var $element = $(this);
                if ($element.hasClass('show')) {
                    $element.removeClass('show');
                }
            });
            return oldShowHide.hide.call(this);
        }
    });
}(window.jQuery);

Bootstrap에이 문제에 대한 수정 프로그램이 제공되면 버립니다.


부트 스트랩 4에서는 d-none클래스를 사용 하여 요소를 완전히 숨길 수 있습니다 . https://getbootstrap.com/docs/4.0/utilities/display/


업데이트 : 지금부터, 내가 사용 .collapse하고 $('.collapse').show().


부트 스트랩 4 알파 6

Bootstrap 4의 경우을 사용해야 .hidden-xs-up합니다.

https://v4-alpha.getbootstrap.com/layout/responsive-utilities/#available-classes

.hidden-*-up 클래스는 뷰포트가 지정된 중단 점 이상일 때 요소를 숨 깁니다. 예를 들어 .hidden-md-up은 중간, 큰 및 초대형 뷰포트에서 요소를 숨 깁니다.

도있다 hiddenHTML5 속성은.

https://v4-alpha.getbootstrap.com/content/reboot/#html5-hidden-attribute

HTML5는 [hidden]이라는 새로운 전역 속성을 추가합니다. 기본 속성은 none입니다. PureCSS에서 아이디어를 차용하면 [hidden] {display : none! important; } 실수로 디스플레이가 재정의되는 것을 방지합니다. [숨겨진]은 IE10에서 기본적으로 지원되지 않지만 CSS의 명시 적 선언은이 문제를 해결합니다.

<input type="text" hidden>

.invisible레이아웃에 영향을주는 것도 있습니다 .

https://v4-alpha.getbootstrap.com/utilities/invisible-content/

.invisible 클래스는 요소의 가시성 만 토글하는 데 사용될 수 있습니다. 즉, 표시가 수정되지 않고 요소가 여전히 문서의 흐름에 영향을 줄 수 있습니다.


hide 및 hidden은 더 이상 사용되지 않으며 나중에 제거되며 더 이상 새 버전에는 존재하지 않습니다. 필요에 따라 d-none / d-sm-none / invisible 등의 클래스를 사용할 수 있습니다. 그들이 제거 된 가능한 이유는 CSS 컨텍스트에서 숨김 / 숨기기가 약간 혼동되기 때문입니다. CSS에서 숨기기 (숨김)는 표시가 아닌 가시성에 사용됩니다. 가시성과 표시는 다릅니다.

가시성 : 숨겨진 클래스가 필요한 경우 가시성 유틸리티에서 보이지 않는 클래스가 필요합니다.

가시성 및 디스플레이 유틸리티를 모두 확인하십시오.

https://getbootstrap.com/docs/4.1/utilities/visibility/

https://getbootstrap.com/docs/4.1/utilities/display/


Bootstrap CSS 파일을 편집하여 문제를 해결했습니다. 문서를 참조하십시오.

.숨는 장소:

.hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1

.hide {
  display: none !important;
}

.hidden은 현재 우리가 사용한다고 생각하지만 실제로는 다음과 같습니다.

.hidden {
  display: none !important;
  visibility: hidden !important;
}

"가시성"으로 인해 jQuery "fadeIn"이 작동하지 않습니다.

따라서 최신 Bootstrap의 경우 .hide는 더 이상 사용되지 않지만 여전히 min.css 파일에 있습니다. 그래서 .hidden AS IS를 그대로두고 ".hide"클래스에서 "! important"를 제거했습니다 (어쨌든 더 이상 사용되지 않는 것으로 가정). 그러나 당신은 또한 당신의 CSS에서 그것을 무시할 수 있습니다. 저는 모든 응용 프로그램이 동일하게 작동하기를 원했기 때문에 Bootstrap CSS 파일을 변경했습니다.

이제 jQuery "fadeIn ()"이 작동합니다.

위의 제안과 비교 하여이 작업을 수행 한 이유는 "removeClass ( '. hide')"객체가 즉시 표시되고 애니메이션을 건너 뛰기 때문입니다. :)

그것이 다른 사람들을 도왔기를 바랍니다.


부트 스트랩, JQuery, 네임 스페이스 ... 간단한 문제는 무엇입니까?

var x = document.getElementById('my-div');
x.className.replace(/\bhide\b/, ''); //remove any hide class
x.style.display = ''; //show
x.style.display = 'none'; //hide

KISS 호환 작은 도우미 기능을 만들 수 있습니다.

function mydisplay(id, display) {
    var node = (typeof id == 'string') ? document.getElementById(id) : id;
    node.className.replace(/\bhide\b/, '');
    if (node) {
        if (typeof display == 'undefined') {
            display = (node.style.display != 'none');
        } else if (typeof display == 'string' && display == 'toggle') {
            display = mydisplay(node, !mydisplay(node));
        } else {
            node.style.display = (display) ? '' : 'none';
        }
    }
    return display;
}
is_hidden = mydisplay('my-div'); //actual state
mydisplay('my-div', false); //hide
mydisplay('my-div', true); //show
mydisplay('my-div', 'toggle'); //toggle state

위의 답변을 바탕으로 방금 내 함수를 추가했으며 .hide (), .show (), .toggle ()과 같은 사용 가능한 jquery 함수와 충돌하지 않습니다. 도움이 되길 바랍니다.

    /*
     * .hideElement()
     * Hide the matched elements. 
     */
    $.fn.hideElement = function(){
        $(this).addClass('hidden');
        return this;
    };

    /*
     * .showElement()
     * Show the matched elements.
     */
    $.fn.showElement = function(){
        $(this).removeClass('hidden');
        return this;
    };

    /*
     * .toggleElement()
     * Toggle the matched elements.
     */
    $.fn.toggleElement = function(){
        $(this).toggleClass('hidden');
        return this;
    };

Twitter Bootstrap은 컨텐츠 토글을위한 클래스를 제공합니다 ( https://github.com/twbs/bootstrap/blob/3ee5542c990817324f0a07b97d01d1fe206fd8d6/less/utilities.less 참조) .

나는 jQuery를 완전히 처음 접했고 거기에서 문서를 읽은 후에 Twitter Bootstrap + jQuery를 결합하는 다른 솔루션을 찾았습니다.

먼저 다른 요소 (클래스 wsis-toggle)를 클릭 할 때 요소 (클래스 wsis-collapse)를 '숨기기'및 '표시'하는 솔루션은 .toggle 을 사용하는 입니다.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle();
    });
});

.wsis-collapseTwitter Bootstrap (V3) 클래스를 사용하여 이미 요소 숨겼습니다 .hidden.

.hidden {
  display: none !important;
  visibility: hidden !important;
}

를 클릭 .wsis-toggle하면 jQuery가 인라인 스타일을 추가합니다.

display: block

때문에의 !important트위터 부트 스트랩에, 우리는 제거해야 할 수 있도록이 인라인 스타일은 아무런 효과가 없습니다 .hidden클래스를,하지만 난 추천하지 않습니다 .removeClass이를 위해! jQuery가 무언가를 다시 숨길 때 인라인 스타일도 추가하기 때문에 :

display: none

이것은 AT (스크린 리더)에도 최적화 된 Twitter 부트 스트랩의 .hidden 클래스와 동일하지 않습니다. 따라서 숨겨진 div를 표시하려면 .hiddenTwitter Bootstrap 클래스를 제거해야 하므로 중요한 진술을 제거하지만 다시 숨기면 .hidden클래스를 다시 만들고 싶습니다 ! 이를 위해 [.toggleClass] [3]을 사용할 수 있습니다.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle().toggleClass( "hidden" );
    });
});

이렇게하면 콘텐츠가 숨겨 질 때마다 숨겨진 클래스를 계속 사용합니다.

.showTB 클래스는 실제로 jQuery의 인라인 스타일과 동일합니다 'display: block'. 그러나 .show어떤 시점에서 수업이 다를 경우이 클래스를 추가하면됩니다.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle().toggleClass( "hidden show" );
    });
});

참고 URL : https://stackoverflow.com/questions/18568736/how-to-hide-element-using-twitter-bootstrap-and-show-it-using-jquery

반응형