如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
当前回答
$( "div:visible" ).click(function() {
$( this ).css( "background", "yellow" );
});
$( "button" ).click(function() {
$( "div:hidden" ).show( "fast" );
});
API 文献资料:可见可见选择器
其他回答
你可以试试这个
$(document).ready(function() {
var view = $(this).is(':visible');
if(view) {
alert("view");
// Code
}
else
{
alert("hidden");
}
});
因为Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout
(截至2004年12月1日jj 查询: 可见选择器- 我们可以检查元素是否真的以这种方式可见:
function isElementReallyHidden (el) {
return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}
var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
if (isElementReallyHidden(this)) {
booElementReallyShowed = false;
}
});
您需要同时检查 显示和可见度 :
if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
// The element is not visible
} else {
// The element is visible
}
如果我们检查$(this).is(":visible")
,j 查询自动检查这两个东西。
如何如何元素可见度和jQuery 工作;
元素可以隐藏display:none
, visibility:hidden
或opacity:0
这些方法之间的差异:
display:none
隐藏元素,且不占用任何空间;visibility:hidden
隐藏元素,但它在布局中仍然占据空间;opacity:0
将元素隐藏为“ 可见性: 隐藏” , 它仍然占载着布局的空间; 唯一的区别在于不透明让一个元素部分透明;
if ($('.target').is(':hidden')) {
$('.target').show();
} else {
$('.target').hide();
}
if ($('.target').is(':visible')) {
$('.target').hide();
} else {
$('.target').show();
}
if ($('.target-visibility').css('visibility') == 'hidden') {
$('.target-visibility').css({
visibility: "visible",
display: ""
});
} else {
$('.target-visibility').css({
visibility: "hidden",
display: ""
});
}
if ($('.target-visibility').css('opacity') == "0") {
$('.target-visibility').css({
opacity: "1",
display: ""
});
} else {
$('.target-visibility').css({
opacity: "0",
display: ""
});
}
有用的 jQuery 切换方法 :
$('.click').click(function() {
$('.target').toggle();
});
$('.click').click(function() {
$('.target').slideToggle();
});
$('.click').click(function() {
$('.target').fadeToggle();
});
此选项可以检查标签是否可见
// 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
// };