如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
当前回答
要检查它是否不可见, 我使用它!
:
if ( !$('#book').is(':visible')) {
alert('#book is not visible')
}
或以下是 sam, 将 jQuery 选择器保存在一个变量中, 以便在您需要它多次时有更好的性能 :
var $book = $('#book')
if(!$book.is(':visible')) {
alert('#book is not visible')
}
其他回答
由于问题只涉及一个要素,本守则可能更适合:
// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");
// The same works with hidden
$(element).is(":hidden");
与twernt的建议,但适用于单一个元素;并且匹配 jQuery FAQ 中推荐的算法.
我们用jQuery的是( )将选中的元素与其它元素、选择器或任何 jQuery 对象一起检查。此方法沿 DOM 元素沿 DOM 元素查找匹配,该匹配符合所传递的参数。如果匹配,则返回为真实,否则返回为虚假。
.is(":not(':hidden')") /*if shown*/
您需要同时检查 显示和可见度 :
if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
// The element is not visible
} else {
// The element is visible
}
如果我们检查$(this).is(":visible")
,j 查询自动检查这两个东西。
此选项可以检查标签是否可见
// using a pure CSS selector
if ($('p:visible')) {
alert('Paragraphs are visible (checked using a CSS selector) !');
};
// using jQuery's is() method
if ($('p').is(':visible')) {
alert('Paragraphs are visible (checked using is() method)!');
};
// using jQuery's filter() method
if ($('p').filter(':visible')) {
alert('Paragraphs are visible (checked using filter() method)!');
};
// you can use :hidden instead of :visible to reverse the logic and check if an element is hidden
// if ($('p:hidden')) {
// do something
// };