如何使元素的可见度.hide(), .show(),或.toggle()?

如果一个元素是visiblehidden?


当前回答

if($(element).is(":visible")) {
  console.log('element is visible');
} else {
  console.log('element is not visible');
}

其他回答

if($('#postcode_div').is(':visible')) {
    if($('#postcode_text').val()=='') {
        $('#spanPost').text('\u00a0');
    } else {
        $('#spanPost').text($('#postcode_text').val());
}

您应该考虑的另一个答案是,如果您隐藏了一个元素,您应该使用jj 查询,但实际上没有隐藏它,而是删除了整个元素,但复制了它HTML HTML输入 jQuery 变量,然后您只需要测试屏幕上是否有这样的标记,然后使用普通if (!$('#thetagname').length).

此选项可以检查标签是否可见

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

因为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($('#id_element').is(":visible")){
   alert('shown');
}else{
   alert('hidden');
}