Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - How to hide element using Twitter Bootstrap and show it using jQuery?

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>

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
  • To show it: $("#myId").removeClass('d-none');
  • To hide it: $("#myId").addClass('d-none');
  • To toggle it: $("#myId").toggleClass('d-none');

(thanks to the comment by Fangming)

Bootstrap 3.x

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...