如何使用Twitter Bootstrap隐藏元素并使用jQuery显示它?

如何使用Twitter Bootstrap隐藏元素并使用jQuery显示它?

问题描述:

假设我创建了一个这样的HTML元素,

Let's say I create an HTML element like this,

<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元素。

How could I show and hide that HTML element from jQuery/Javascript.

JavaScript:

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

结果:(包含其中任何一项)。

Result: (with any of these).

我希望隐藏上面的元素。

I would like the elements above to be hidden.

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

What is simplest way to hide element using Bootstrap and show it using jQuery?

正确答案



Bootstrap 4.x



Bootstrap 4.x使用新的 .d-none 而不是使用 .hidden ,或 .hide 如果你是使用Bootstrap 4.x使用 .d-none

The right answer

Bootstrap 4.x

Bootstrap 4.x uses the new .d-none class. Instead of using either .hidden, or .hide if you're using Bootstrap 4.x use .d-none.

<div id="myId" class="d-none">Foobar</div>




  • 要显示: $(# myId)。removeClass('d-none');

  • 隐藏它: $(#myId)。addClass ('d-none');

  • 要切换它: $(#myId)。toggleClass('d-none ');

    • To show it: $("#myId").removeClass('d-none');
    • To hide it: $("#myId").addClass('d-none');
    • To toggle it: $("#myId").toggleClass('d-none');
    • (感谢方明的评论)

      首先,不要使用 .hide 使用 .hidden 正如其他人所说, .hide 已被弃用,

      First, don't use .hide! Use .hidden. As others have said, .hide is deprecated,


      .hide可用,但它并不总是影响屏幕阅读器,自v3.0.1起不推荐使用

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

      其次,使用jQuery的 .toggleClass() .addClass()。removeClass()

      Second, use jQuery's .toggleClass(), .addClass() and .removeClass()

<div id="myId" class="hidden">Foobar</div>




  • 要显示: $(# myId)。removeClass('hidden');

  • 隐藏它: $(#myId)。addClass('隐藏');

  • 要切换它: $(#myId)。toggleClass('hidden');

    • To show it: $("#myId").removeClass('hidden');
    • To hide it: $("#myId").addClass('hidden');
    • To toggle it: $("#myId").toggleClass('hidden');
    • 不要使用css类 .show ,它有一个非常小的用例。 显示隐藏隐藏的定义属于 docs

      Don't use the css class .show, it has a very small use case. The definitions of show, hidden and invisible are in the docs.

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