且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用twitter bootstrap 3隐藏元素并使用jQuery显示它?

更新时间:2022-11-10 19:08:27

正确答案



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



blockquote>

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

 < div id =myIdclass =hidden> Foobar< / div> 




  • 显示: $要隐藏它: $(#myId)。addClass('myId)removeClass('hidden');


  • 要切换它: $(#myId)。toggleClass c $ c>



不要使用css类 .show 它有一个非常小的用例。 显示 hidden 不可见的定义位于文档

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


With Twitter Bootstrap 3 and jQuery 2.0.3

HTML:

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

Javascript:

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

Result:

Invisible my-div

<div id="my-div" class="hide" style="display: block;">Hello, TB3</div>

The reason:

.hide {
    display: none !important;
}

bootstrap.min.js, line 9

Question:

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

The right answer

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

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

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

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

  • To show it: $("#myId").removeClass('hidden');
  • To hide it: $("#myId").addClass('hidden');
  • To toggle it: $("#myId").toggleClass('hidden');

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