隐藏 css 类的 jQuery show() Bootstrap

我使用的是 Bootstrap,我注意到 jQuery show()或者 fadeIn()没有显示带有类 hidden标记的 DOM 元素,因为 jQuery 函数只删除了 display: none规范。但是,visibility仍然被设置为 hidden

我想知道解决这个问题的最好方法是什么?

  1. 删除元素上的 hidden
  2. 更改可见性属性
  3. 在我自己的 css 中覆盖隐藏类

特别是,我想知道用 jQuery 还是 css 修复这个问题是否更好,以及为什么。

61309 次浏览

This will fade your invisible element in and remove the class

$('#element.hidden').css('visibility','visible').hide().fadeIn().removeClass('hidden');

http://jsfiddle.net/7qxVL/

If you don't really need the element to be invisible (ie take up the space) tho you might wanna redefine .hidden (in you local css, don't change bootstrap source, or even better, in your local LESS file).

I had the same problem. I used this patch:

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

Then I had another problem, since my application generates new elements and append/prepend them. What I finally did is after genereting the new element I do:

var newEl = ...;
$(newEl).find('.hidden').hide().removeClass('hidden');

The css class you're looking for is .collapse. This sets the element to display: none;

So using $('#myelement').show() will work properly.

Bootstrap v3.3.6 has updated .collapse back to:

.collapse {
display: none;
}

For me it was because bootstrap is using the !important hack for both class hide and hidden.

So you can't use the show() etc methods provided with jquery. Instead you have to overwrite even more horrible code overwriting the hacky code.

$('#myelement').attr('style', 'display: block !important');

!important is a last resort option and really shouldn't be used in a core library like bootstrap.

Warning:

bootstrap 3.3.0 just changed .collapse to:

.collapse {
display: none;
visibility: hidden;
}

Which is a breaking change for jQuery.show() I had to revert back to inlining:

<div class="alert alert-danger" style="display:none;" >
</div>

to continue using jQuery as follows:

$('.alert').html("Change a few things up and try submitting again.").show()

The only class I could find in bootstrap 3.3.0 to apply just 'display:none' is

.navbar {
display: none;
}

This works, but I'm going to try the first answer and change the classes to .collapse.

.toggleClass('hidden')