【问题标题】:How to hide element using Twitter Bootstrap and show it using jQuery?如何使用 Twitter Bootstrap 隐藏元素并使用 jQuery 显示它?
【发布时间】:2026-01-23 11:15:01
【问题描述】:

假设我创建了一个这样的 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 元素。

JavaScript:

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

结果:(其中任何一个)。

我想隐藏上面的元素。

使用 Bootstrap 隐藏元素并使用 jQuery 显示元素的最简单方法是什么?

【问题讨论】:

  • 为了保持这个问题的相关性,我已经修改它以在两个 Bootstrap 上工作,因为答案只是类名的不同。

标签: javascript jquery html css twitter-bootstrap


【解决方案1】:

正确答案

引导程序 4.x

Bootstrap 4.x uses the new .d-none class如果您使用的是 Bootstrap 4.x,请使用.d-none,而不是使用.hidden.hide,而不是使用.d-none

<div id="myId" class="d-none">Foobar</div>
  • 显示它:$("#myId").removeClass('d-none');
  • 隐藏它:$("#myId").addClass('d-none');
  • 切换它:$("#myId").toggleClass('d-none');

(感谢方明的评论)

引导程序 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,它的用例非常小。 showhiddeninvisible的定义在docs中。

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

【讨论】:

  • 非常感谢,我很长时间以来一直想知道 * 是否有这样的简单答案。谢谢
  • 任何人都知道方法是什么:show() 和 hide() 用于 then 吗?
  • 那么你不能为它制作动画(例如fadeIn())。因此使用类collapse 而不是hidden。然后当然不需要使用removeClassaddClass等。
  • 对于 Bootstrap 4,您必须使用 .hidden-xs-upv4-alpha.getbootstrap.com/layout/responsive-utilities/… 还有hidden HTML5 属性。 v4-alpha.getbootstrap.com/content/reboot/…
  • @Kangur jQuery .hide() 不是引导程序的 .hide 类。 jQuery 方法工作正常,但它不是引导方式。 Bootstrap 库依赖于元素上包含的 .hidden 类来确定它不存在。 jQuery 没有添加它——除非你像这里一样破解它:*.com/a/27439371/124486,在这种情况下你可能会破坏其他 jQuery 特定的东西。
【解决方案2】:

简单地说:

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

或者,如果您希望课程仍然存在:

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

【讨论】:

  • 这是一个 jQuery 插件,它允许您使用 .show() 和 .hide() ,即使是引导程序“hidden”和“hide”类。 gist.github.com/zimkies/8360181
  • 根据 Bootstrap 文档,.hide 是可用的,但它并不总是影响屏幕阅读器,并且从 v3.0.1 开始已弃用。请改用 .hidden 或 .sr-only。
【解决方案3】:

使用引导程序 .collapse 而不是 .hidden

稍后在 JQuery 中,您可以使用 .show() 或 .hide() 来操作它

【讨论】:

    【解决方案4】:

    此解决方案已弃用。使用票数最高的解决方案。

    hide 类有助于在页面加载时隐藏内容。

    我的解决办法是在初始化的时候,切换到jquery的隐藏:

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

    那么show()hide() 应该会正常工作。

    【讨论】:

    • .hide 自 v3.0.1 起已弃用
    • 好的,从 v3.0.1 开始使用 .hidden
    • 在这种情况下,可能会出现闪烁的内容,在被 JS 隐藏之前会显示几微秒。
    • 调用 .hide() 首先应用 display:none;到样式标签。这发生在删除隐藏类之前。如果你按这个顺序,它不应该闪烁。
    【解决方案5】:

    解决这个烦恼的另一种方法是创建自己的 CSS 类,它不会在规则末尾设置 !important,如下所示:

    .hideMe {
        display: none;
    }
    

    并像这样使用:

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

    现在 jQuery 隐藏可以工作了

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

    【讨论】:

    • 它规避了使用引导类所带来的问题。为什么要否决这个简短而简单的解决方案?
    • 因为这个简短而简单的解决方案没有回答专门要求使用 bootstrap3 类的问题。更不用说,虽然简单,但 .hidden 在 Bootstrap is defined as .hidden { display: none !important; visibility: hidden !important; }
    • 这正是问题所在,JQuery 的隐藏和显示方法不适用于这个 css。
    【解决方案6】:

    @dustin-graham 概述的方法也是我的做法。另请记住,根据他们在getbootstrap 的文档,bootstrap 3 现在使用“隐藏”而不是“隐藏”。所以我会做这样的事情:

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

    那么每当使用 jQuery 的show()hide() 方法时,就不会有冲突了。

    【讨论】:

    • 如此优雅和简单——你刚刚克服了一个常见的 Bootstrap 缺陷。我会使用hidden 类,然后尝试在jQuery 中执行show(),但什么都不会发生。您的解决方案如此轻松地解决了这个问题,而我没有想到。
    【解决方案7】:

    使用以下方式启动元素:

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

    然后,使用您要显示的事件,如下所示:

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

    我相信最简单的方法。

    【讨论】:

      【解决方案8】:

      HTML:

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

      Javascript:

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

      【讨论】:

        【解决方案9】:

        我喜欢使用toggleClass:

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

        【讨论】:

        • 这很好,但switch 完全不需要。
        【解决方案10】:
        $(function(){
        
        $("#my-div").toggle();
        
        $("#my-div").click(function(){$("#my-div").toggle()})
        
        })
        

        // 您甚至不必设置#my-div .hide!important,只需在事件函数中粘贴/重复切换即可。

        【讨论】:

          【解决方案11】:

          最近从 2.3 升级到 3.1 时遇到了这个问题;我们的 jQuery 动画 (slideDown) 坏了,因为我们将 hide 放在页面模板中的元素上。我们创建了 Bootstrap 类的命名空间版本,这些版本现在带有丑陋的 !important 规则。

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

          【讨论】:

          • 3.1 不支持 .hide,它有 .hidden。
          【解决方案12】:

          如果你愿意重写你所做的事情,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 提供解决此问题的方法时将其丢弃。

          【讨论】:

          • 在调用.removeClass().addClass() 之前检查类是否存在是必要的还是最佳的?
          • 另外,.removeClass() 不是已经在集合上工作了吗?你不能简单地打电话给$(this).removeClass('show')
          【解决方案13】:

          在 bootstrap 4 中,您可以使用 d-none 类完全隐藏元素。 https://getbootstrap.com/docs/4.0/utilities/display/

          【讨论】:

            【解决方案14】:

            更新:从现在开始,我使用.collapse$('.collapse').show()


            对于 Bootstrap 4 Alpha 6

            对于 Bootstrap 4,您必须使用 .hidden-xs-up

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

            当视口位于给定断点或更宽时,.hidden-*-up 类隐藏元素。例如,.hidden-md-up 在中、大和超大视口上隐藏元素。

            还有hidden HTML5 属性。

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

            HTML5 添加了一个名为 [hidden] 的新全局属性,其样式默认为 display: none。借用 PureCSS 的一个想法,我们改进了这个默认设置 [hidden] { display: none !important; } 以帮助防止其显示被意外覆盖。虽然 IE10 本身不支持 [hidden],但我们的 CSS 中的显式声明解决了这个问题。

            &lt;input type="text" hidden&gt;

            还有.invisible 确实会影响布局。

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

            .invisible 类只能用于切换元素的可见性,这意味着它的显示不会被修改,并且该元素仍然可以影响文档的流动。

            【讨论】:

              【解决方案15】:

              对扩展 jQuery 的 Bootstrap 4 使用以下 sn-p:

              (function( $ ) {
              
                  $.fn.hideShow = function( action ) {
              
                      if ( action.toUpperCase() === "SHOW") {
                          // show
                          if(this.hasClass("d-none"))
                          {
                              this.removeClass("d-none");
                          }
              
                          this.addClass("d-block");
              
                      }
              
                      if ( action.toUpperCase() === "HIDE" ) {
                          // hide
                          if(this.hasClass("d-block"))
                          {
                              this.removeClass("d-block");
                          }
              
                          this.addClass("d-none");
                    }
              
                        return this;
                  };
              
              }( jQuery ));
              
              1. 将上述代码放入文件中。让我们假设“myJqExt.js”
              2. 在包含 jQuery 之后再包含文件。

              3. 使用语法来使用它

                $().hideShow('隐藏');

                $().hideShow('show');

              希望对大家有所帮助。 :-)

              【讨论】:

                【解决方案16】:

                hide 和 hidden 都已弃用,后来又被删除,在新版本中不再存在。您可以根据需要使用 d-none/d-sm-none/invisible 等类。 它们被删除的可能原因是因为隐藏/隐藏在 CSS 上下文中有点混乱。在 CSS 中,隐藏(hidden)是用于可见性,而不是用于显示。 可见性和显示是不同的东西。

                如果您需要一个可见性类:隐藏,那么您需要可见性实用程序中的不可见类。

                检查以下可见性和显示实用程序:

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

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

                【讨论】:

                  【解决方案17】:

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

                  【讨论】:

                    【解决方案18】:

                    根据上面的答案,我刚刚添加了自己的函数,这进一步不会与可用的 jquery 函数如 .hide()、.show()、.toggle() 冲突。希望对您有所帮助。

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

                    【讨论】:

                      【解决方案19】:

                      我通过编辑 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 原样,只是从“.hide”类中删除了“!important”(无论如何都应该弃用)。但你也可以在你自己的 CSS 中覆盖它,我只是希望我的所有应用程序都可以运行,所以我更改了 Bootstrap CSS 文件。

                      现在 jQuery "fadeIn()" 可以工作了。

                      与上面的建议相比,我这样做的原因是,当您“removeClass('.hide')”时,对象会立即显示出来,并且您会跳过动画:)

                      我希望它对其他人有所帮助。

                      【讨论】:

                        【解决方案20】:

                        ☀️ 正确答案

                        在 Bootstrap 4 中你隐藏了元素:

                        <p id="insufficient-balance-warning" class="d-none alert alert-danger">Pay me</p>
                        

                        ? 然后,当然,你可以用以下方式展示它:

                        if (pizzaFundsAreLow) {
                          $('#insufficient-balance-warning').removeClass('d-none');
                        }
                        

                        ? 但是如果你以语义的方式来做,通过将责任从 Bootstrap 转移到 jQuery,那么你可以使用其他 jQuery 细节,比如褪色:

                        if (pizzaFundsAreLow) {
                          $('#insufficient-balance-warning').hide().removeClass('d-none').fadeIn();
                        }
                        

                        【讨论】:

                          【解决方案21】:

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

                          您已经使用 Twitter Bootstrap (V3) 类 .hidden 隐藏了元素 .wsis-collapse

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

                          当你点击.wsis-toggle 时,jQuery 正在添加一个内联样式:

                          display: block
                          

                          由于 Twitter Bootstrap 中的!important,这种内联样式没有效果,所以我们需要删除.hidden 类,但我不会为此推荐.removeClass!因为当 jQuery 要再次隐藏某些东西时,它也会添加一个内联样式:

                          display: none
                          

                          这与 Twitter Bootstrap 的 .hidden 类不同,后者也针对 AT 进行了优化(屏幕阅读器)。所以,如果我们想显示隐藏的div,我们需要去掉Twitter Bootstrap的.hidden类,所以我们去掉了重要的语句,但是如果我们再次隐藏它,我们想要.hidden又上课了!我们可以为此使用 [.toggleClass][3]。

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

                          这样你每次隐藏内容时都使用隐藏类。

                          TB中的.show类其实和jQuery的内联样式是一样的,都是'display: block'。但如果 .show 类在某些时候会有所不同,那么您只需添加这个类即可:

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

                          【讨论】:

                          • @EvanCarroll,为什么这么复杂?我也一直在阅读您的答案,我看到您建议使用 toggleClass 我也这样做,所以我不明白您的评论。