如何检查 jQuery 中的元素是否隐藏?

发布于 2024-07-07 01:08:45 字数 138 浏览 10 评论 0原文

如何使用 .hide().show().toggle() 切换元素的可见性?

如何测试元素是可见还是隐藏

How do I toggle the visibility of an element using .hide(), .show(), or .toggle()?

How do I test if an element is visible or hidden?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

内心旳酸楚 2024-07-14 01:08:46
if($('#postcode_div').is(':visible')) {
    if($('#postcode_text').val()=='') {
        $('#spanPost').text('\u00a0');
    } else {
        $('#spanPost').text($('#postcode_text').val());
}
if($('#postcode_div').is(':visible')) {
    if($('#postcode_text').val()=='') {
        $('#spanPost').text('\u00a0');
    } else {
        $('#spanPost').text($('#postcode_text').val());
}
关于从前 2024-07-14 01:08:46

另外,这里还有一个三元条件表达式,用于检查元素的状态,然后切换它:

$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });

Also here's a ternary conditional expression to check the state of the element and then to toggle it:

$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });
惟欲睡 2024-07-14 01:08:45

由于问题涉及单个元素,因此此代码可能更合适:

// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");

// The same works with hidden
$(element).is(":hidden");

它与 twernt 的建议,但应用于单个元素; 并且它与推荐的算法匹配在 jQuery 常见问题解答中。

我们使用 jQuery 的 is() 来检查所选元素与另一个元素、选择器或任何 jQuery 对象。 该方法沿着 DOM 元素遍历以查找满足传递参数的匹配项。 如果匹配则返回 true,否则返回 false。

Since the question refers to a single element, this code might be more suitable:

// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");

// The same works with hidden
$(element).is(":hidden");

It is the same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ.

We use jQuery's is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false.

泪冰清 2024-07-14 01:08:45

在 jQuery 中针对 :hidden 选择器测试元素时,应考虑到绝对定位元素可能会被识别为隐藏,尽管其子元素可见

首先,这似乎有点违反直觉——尽管仔细查看 jQuery 文档会给出相关信息:

元素可以被视为隐藏,原因如下:[...]它们的宽度和高度显式设置为 0。[...]

因此,这对于框模型和元素的计算样式实际上是有意义的。 即使宽度和高度没有显式设置为0,它们也可以隐式设置。

看一下下面的例子:

console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
  position: absolute;
  left: 10px;
  top: 10px;
  background: #ff0000;
}

.bar {
  position: absolute;
  left: 10px;
  top: 10px;
  width: 20px;
  height: 20px;
  background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
  <div class="bar"></div>
</div>


jQuery 3.x 更新:

使用 jQuery 3,所描述的行为将会改变! 如果元素具有任何布局框(包括零宽度和/或高度的布局框),则元素将被视为可见。

JSFiddle 与 jQuery 3.0.0-alpha1:

http://jsfiddle.net/pM2q3/7/

相同的 JavaScript 代码将具有以下输出:

console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false

When testing an element against :hidden selector in jQuery it should be considered that an absolute positioned element may be recognized as hidden although their child elements are visible.

This seems somewhat counter-intuitive in the first place – though having a closer look at the jQuery documentation gives the relevant information:

Elements can be considered hidden for several reasons: [...] Their width and height are explicitly set to 0. [...]

So this actually makes sense in regards to the box-model and the computed style for the element. Even if width and height are not set explicitly to 0 they may be set implicitly.

Have a look at the following example:

console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
  position: absolute;
  left: 10px;
  top: 10px;
  background: #ff0000;
}

.bar {
  position: absolute;
  left: 10px;
  top: 10px;
  width: 20px;
  height: 20px;
  background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
  <div class="bar"></div>
</div>


Update for jQuery 3.x:

With jQuery 3 the described behavior will change! Elements will be considered visible if they have any layout boxes, including those of zero width and/or height.

JSFiddle with jQuery 3.0.0-alpha1:

http://jsfiddle.net/pM2q3/7/

The same JavaScript code will then have this output:

console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false
傲娇萝莉攻 2024-07-14 01:08:45

您应该考虑的另一个答案是,如果您要隐藏元素,则应该使用 jQuery,但是您没有实际隐藏它,而是删除整个元素,但复制其 HTML 内容和标签将其自身放入 jQuery 变量中,然后您需要做的就是使用普通的 if (!$('#thetagname').length) 测试屏幕上是否存在这样的标签。

Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length).

一身骄傲 2024-07-14 01:08:45

您可以简单地使用 hiddenvisible 属性,例如:

$('element:hidden')
$('element:visible')

或者您可以使用 is 进行简化,如下所示。

$(element).is(":visible")

One can simply use the hidden or visible attribute, like:

$('element:hidden')
$('element:visible')

Or you can simplify the same with is as follows.

$(element).is(":visible")
留一抹残留的笑 2024-07-14 01:08:45

您可以使用 隐藏 选择器:

// Matches all elements that are hidden
$('element:hidden')

以及 可见选择器:

// Matches all elements that are visible
$('element:visible')

You can use the hidden selector:

// Matches all elements that are hidden
$('element:hidden')

And the visible selector:

// Matches all elements that are visible
$('element:visible')
飘逸的'云 2024-07-14 01:08:45
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // 'element' is hidden
}

上述方法没有考虑父级的可见性。 要同时考虑父级,您应该使用 .is(":hidden").is(":visible")

例如,

<div id="div1" style="display:none">
  <div id="div2" style="display:block">Div2</div>
</div>

上述方法将认为 div2 可见,而 :visible 不可见。 但上述内容在许多情况下可能很有用,特别是当您需要查找隐藏父级中是否有任何可见的错误 div 时,因为在这种情况下 :visible 将不起作用。

if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // 'element' is hidden
}

The above method does not consider the visibility of the parent. To consider the parent as well, you should use .is(":hidden") or .is(":visible").

For example,

<div id="div1" style="display:none">
  <div id="div2" style="display:block">Div2</div>
</div>

The above method will consider div2 visible while :visible not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions :visible will not work.

浅笑轻吟梦一曲 2024-07-14 01:08:45

根据 jQuery 文档:visible 选择器:

  • 它们的 CSS display 值为 none
  • 它们是带有 type="hidden" 的表单元素。
  • 它们的宽度和高度明确设置为 0。
  • 祖先元素被隐藏,因此该元素不会显示在页面上。

具有 visibility:hiddenopacity:0 的元素被视为可见,因为它们仍然占用布局中的空间。

这在某些情况下很有用,但在其他情况下没用,因为如果您想检查元素是否可见(display != none),忽略父元素的可见性,您会发现执行 . css("display") == 'none' 不仅更快,而且还能正确返回可见性检查。

如果您想检查可见性而不是显示,则应使用:.css("visibility") == "hidden"

另请考虑附加 jQuery 注释

由于 :visible 是 jQuery 扩展,而不是 CSS 规范的一部分,因此使用 :visible 的查询无法利用本机 DOM querySelectorAll() 方法。 为了在使用 :visible 选择元素时获得最佳性能,请首先使用纯 CSS 选择器选择元素,然后使用 .filter(":visible")。 p>

另外,如果您担心性能,您应该检查现在你看到我了...显示/隐藏性能 (2010-05-04)。 并使用其他方法来显示和隐藏元素。

The :visible selector according to the jQuery documentation:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.

This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none), ignoring the parents visibility, you will find that doing .css("display") == 'none' is not only faster, but will also return the visibility check correctly.

If you want to check visibility instead of display, you should use: .css("visibility") == "hidden".

Also take into consideration the additional jQuery notes:

Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").

Also, if you are concerned about performance, you should check Now you see me… show/hide performance (2010-05-04). And use other methods to show and hide elements.

若相惜即相离 2024-07-14 01:08:45

通常,当检查某些东西是否可见时,您会立即继续并用它做其他事情。 jQuery 链接使这一切变得简单。

因此,如果您有一个选择器,并且只想在可见或隐藏时对其执行某些操作,则可以使用 filter(":visible")filter(":hidden") 然后将其与您要执行的操作链接起来。

因此,不要使用 if 语句,如下所示:

if ($('#btnUpdate').is(":visible"))
{
     $('#btnUpdate').animate({ width: "toggle" });   // Hide button
}

或者更有效:

var button = $('#btnUpdate');
if (button.is(":visible"))
{
     button.animate({ width: "toggle" });   // Hide button
}

您可以在一行中完成所有操作:

$('#btnUpdate').filter(":visible").animate({ width: "toggle" });

Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.

So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible") or filter(":hidden") followed by chaining it with the action you want to take.

So instead of an if statement, like this:

if ($('#btnUpdate').is(":visible"))
{
     $('#btnUpdate').animate({ width: "toggle" });   // Hide button
}

Or more efficiently:

var button = $('#btnUpdate');
if (button.is(":visible"))
{
     button.animate({ width: "toggle" });   // Hide button
}

You can do it all in one line:

$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
梦里人 2024-07-14 01:08:45

来自 如何确定切换元素的状态?


您可以使用 :visible确定元素是否折叠:隐藏的选择器。

var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');

如果您只是根据元素的可见性对其进行操作,则只需在选择器表达式中包含 :visible:hidden 即可。 例如:

 $('#myDiv:visible').animate({left: '+=200px'}, 'slow');

From How do I determine the state of a toggled element?


You can determine whether an element is collapsed or not by using the :visible and :hidden selectors.

var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');

If you're simply acting on an element based on its visibility, you can just include :visible or :hidden in the selector expression. For example:

 $('#myDiv:visible').animate({left: '+=200px'}, 'slow');
很酷不放纵 2024-07-14 01:08:45

这些答案都没有解决我所理解的问题,这就是我正在寻找的问题,“如何处理具有可见性:隐藏的项目?”。 :visible:hidden 都不会处理这个问题,因为它们都在根据文档寻找显示。 据我所知,没有选择器来处理 CSS 可见性。 这是我解决它的方法(标准 jQuery 选择器,可能有更简洁的语法):

$(".item").each(function() {
    if ($(this).css("visibility") == "hidden") {
        // handle non visible state
    } else {
        // handle visible state
    }
});

None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden?". Neither :visible nor :hidden will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):

$(".item").each(function() {
    if ($(this).css("visibility") == "hidden") {
        // handle non visible state
    } else {
        // handle visible state
    }
});
你如我软肋 2024-07-14 01:08:45

我会使用 CSS class .hide { display: none!important; }

对于隐藏/显示,我调用 .addClass("hide")/.removeClass("hide")。 为了检查可见性,我使用 .hasClass("hide")

如果您不打算使用 .toggle().animate() 方法,这是一种检查/隐藏/显示元素的简单明了的方法。

I would use CSS class .hide { display: none!important; }.

For hiding/showing, I call .addClass("hide")/.removeClass("hide"). For checking visibility, I use .hasClass("hide").

It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle() or .animate() methods.

鹿童谣 2024-07-14 01:08:45

演示链接

$('#clickme').click(function() {
  $('#book').toggle('slow', function() {
    // Animation complete.
    alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
  Click here
</div>
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>

来源(来自我的博客):

Blogger 即插即用 - jQuery 工具和小部件:如何使用 jQuery 查看元素是否隐藏或可见

Demo Link

$('#clickme').click(function() {
  $('#book').toggle('slow', function() {
    // Animation complete.
    alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
  Click here
</div>
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>

Source (from my blog):

Blogger Plug n Play - jQuery Tools and Widgets: How to See if Element is hidden or Visible Using jQuery

惜醉颜 2024-07-14 01:08:45

这对我有用,我使用 show()hide() 使我的 div 隐藏/可见:

if( $(this).css('display') == 'none' ){
    /* your code goes here */
} else {
    /* alternate logic   */
}

This works for me, and I am using show() and hide() to make my div hidden/visible:

if( $(this).css('display') == 'none' ){
    /* your code goes here */
} else {
    /* alternate logic   */
}
别低头,皇冠会掉 2024-07-14 01:08:45

您还可以使用纯 JavaScript 来执行此操作:

function isRendered(domObj) {
    if ((domObj.nodeType != 1) || (domObj == document.body)) {
        return true;
    }
    if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
        return isRendered(domObj.parentNode);
    } else if (window.getComputedStyle) {
        var cs = document.defaultView.getComputedStyle(domObj, null);
        if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
            return isRendered(domObj.parentNode);
        }
    }
    return false;
}

注意:

  1. 适用于任何地方

  2. 适用于嵌套元素

  3. 适用于 CSS 和内联样式

  4. 不需要框架

You can also do this using plain JavaScript:

function isRendered(domObj) {
    if ((domObj.nodeType != 1) || (domObj == document.body)) {
        return true;
    }
    if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
        return isRendered(domObj.parentNode);
    } else if (window.getComputedStyle) {
        var cs = document.defaultView.getComputedStyle(domObj, null);
        if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
            return isRendered(domObj.parentNode);
        }
    }
    return false;
}

Notes:

  1. Works everywhere

  2. Works for nested elements

  3. Works for CSS and inline styles

  4. Doesn't require a framework

夏夜暖风 2024-07-14 01:08:45

元素可见性和 jQuery 的工作原理;

可以使用 display:nonevisibility:hiddenopacity:0 隐藏元素。 这些方法的区别:

  • display:none 隐藏元素,并且不占用任何空间;
  • visibility:hidden 隐藏元素,但它仍然占用布局中的空间;
  • opacity:0 将元素隐藏为“visibility:hidden”,但它仍然占用布局中的空间; 唯一的区别是不透明度可以使元素部分透明;

    if ($('.target').is(':hidden')) { 
        $('.target').show(); 
      } 别的 { 
        $('.target').hide(); 
      } 
      if ($('.target').is(':visible')) { 
        $('.target').hide(); 
      } 别的 { 
        $('.target').show(); 
      } 
    
      if ($('.target-visibility').css('visibility') == '隐藏') { 
        $('.目标可见性').css({ 
          可见性:“可见”, 
          展示: ”” 
        }); 
      } 别的 { 
        $('.目标可见性').css({ 
          可见性:“隐藏”, 
          展示: ”” 
        }); 
      } 
    
      if ($('.target-visibility').css('opacity') == "0") { 
        $('.目标可见性').css({ 
          不透明度:“1”, 
          展示: ”” 
        }); 
      } 别的 { 
        $('.目标可见性').css({ 
          不透明度:“0”, 
          展示: ”” 
        }); 
      } 
      

    有用的 jQuery 切换方法:

    $('.click').click(function() { 
        $('.target').toggle(); 
      }); 
    
      $('.click').click(function() { 
        $('.target').slideToggle(); 
      }); 
    
      $('.click').click(function() { 
        $('.target').fadeToggle(); 
      }); 
      

How element visibility and jQuery works;

An element could be hidden with display:none, visibility:hidden or opacity:0. The difference between those methods:

  • display:none hides the element, and it does not take up any space;
  • visibility:hidden hides the element, but it still takes up space in the layout;
  • opacity:0 hides the element as "visibility:hidden", and it still takes up space in the layout; the only difference is that opacity lets one to make an element partly transparent;

    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: ""
      });
    }
    

    Useful jQuery toggle methods:

    $('.click').click(function() {
      $('.target').toggle();
    });
    
    $('.click').click(function() {
      $('.target').slideToggle();
    });
    
    $('.click').click(function() {
      $('.target').fadeToggle();
    });
    
黄昏下泛黄的笔记 2024-07-14 01:08:45

ebdiv 应设置为 style="display:none;"。 它适用于显示和隐藏:

$(document).ready(function(){
    $("#eb").click(function(){
        $("#ebdiv").toggle();
    });    
});

ebdiv should be set to style="display:none;". It works for both show and hide:

$(document).ready(function(){
    $("#eb").click(function(){
        $("#ebdiv").toggle();
    });    
});
终弃我 2024-07-14 01:08:45

使用可见检查广告拦截器是否已激活的示例:

$(document).ready(function(){
  if(!$("#ablockercheck").is(":visible"))
    $("#ablockermsg").text("Please disable adblocker.").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>

“ablockercheck”是adblocker 阻止的ID。 因此,检查它是否可见,您就可以检测广告拦截器是否已打开。

Example of using the visible check for adblocker is activated:

$(document).ready(function(){
  if(!$("#ablockercheck").is(":visible"))
    $("#ablockermsg").text("Please disable adblocker.").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>

"ablockercheck" is a ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.

红墙和绿瓦 2024-07-14 01:08:45

毕竟没有一个例子适合我,所以我自己写了。

测试(不支持 Internet Explorer filter:alpha):

a) 检查文档是否未隐藏

b) 检查元素的宽度/高度/不透明度是否为零内联样式中的 display:none / visibility:hidden

c) 检查元素的中心(也因为它比测试每个像素/角更快)是否没有被其他元素隐藏元素(以及所有祖先,例如:overflow:hidden /滚动/一个元素覆盖另一个元素)或屏幕边缘

d) 检查元素是否具有零宽度/高度/不透明度或display:none< /code> / 可见性:隐藏在计算样式中(在所有祖先中)

Android 4.4(本机浏览器/Chrome/Firefox)、Firefox (Windows/Mac)、Chrome (Windows/Mac)、Opera 上测试(Windows Presto/Mac WebKit)、Internet Explorer (Internet Explorer 5- 11 种文档模式 + 虚拟机上的 Internet Explorer 8)和 Safari (Windows/Mac/iOS)。

var is_visible = (function () {
    var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,
        y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,
        relative = !!((!x && !y) || !document.elementFromPoint(x, y));
        function inside(child, parent) {
            while(child){
                if (child === parent) return true;
                child = child.parentNode;
            }
        return false;
    };
    return function (elem) {
        if (
            document.hidden ||
            elem.offsetWidth==0 ||
            elem.offsetHeight==0 ||
            elem.style.visibility=='hidden' ||
            elem.style.display=='none' ||
            elem.style.opacity===0
        ) return false;
        var rect = elem.getBoundingClientRect();
        if (relative) {
            if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;
        } else if (
            !inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||
            (
                rect.top + elem.offsetHeight/2 < 0 ||
                rect.left + elem.offsetWidth/2 < 0 ||
                rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||
                rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)
            )
        ) return false;
        if (window.getComputedStyle || elem.currentStyle) {
            var el = elem,
                comp = null;
            while (el) {
                if (el === document) {break;} else if(!el.parentNode) return false;
                comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
                if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;
                el = el.parentNode;
            }
        }
        return true;
    }
})();

如何使用:

is_visible(elem) // boolean

After all, none of examples suits me, so I wrote my own.

Tests (no support of Internet Explorer filter:alpha):

a) Check if the document is not hidden

b) Check if an element has zero width / height / opacity or display:none / visibility:hidden in inline styles

c) Check if the center (also because it is faster than testing every pixel / corner) of element is not hidden by other element (and all ancestors, example: overflow:hidden / scroll / one element over another) or screen edges

d) Check if an element has zero width / height / opacity or display:none / visibility:hidden in computed styles (among all ancestors)

Tested on

Android 4.4 (Native browser/Chrome/Firefox), Firefox (Windows/Mac), Chrome (Windows/Mac), Opera (Windows Presto/Mac WebKit), Internet Explorer (Internet Explorer 5-11 document modes + Internet Explorer 8 on a virtual machine), and Safari (Windows/Mac/iOS).

var is_visible = (function () {
    var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,
        y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,
        relative = !!((!x && !y) || !document.elementFromPoint(x, y));
        function inside(child, parent) {
            while(child){
                if (child === parent) return true;
                child = child.parentNode;
            }
        return false;
    };
    return function (elem) {
        if (
            document.hidden ||
            elem.offsetWidth==0 ||
            elem.offsetHeight==0 ||
            elem.style.visibility=='hidden' ||
            elem.style.display=='none' ||
            elem.style.opacity===0
        ) return false;
        var rect = elem.getBoundingClientRect();
        if (relative) {
            if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;
        } else if (
            !inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||
            (
                rect.top + elem.offsetHeight/2 < 0 ||
                rect.left + elem.offsetWidth/2 < 0 ||
                rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||
                rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)
            )
        ) return false;
        if (window.getComputedStyle || elem.currentStyle) {
            var el = elem,
                comp = null;
            while (el) {
                if (el === document) {break;} else if(!el.parentNode) return false;
                comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
                if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;
                el = el.parentNode;
            }
        }
        return true;
    }
})();

How to use:

is_visible(elem) // boolean
笑叹一世浮沉 2024-07-14 01:08:45
$(document).ready(function() {
  if ($("#checkme:hidden").length) {
    console.log('Hidden');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
  <span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
  <br>Product: Salmon Atlantic
  <br>Specie: Salmo salar
  <br>Form: Steaks
</div>

$(document).ready(function() {
  if ($("#checkme:hidden").length) {
    console.log('Hidden');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
  <span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
  <br>Product: Salmon Atlantic
  <br>Specie: Salmo salar
  <br>Form: Steaks
</div>

吾家有女初长成 2024-07-14 01:08:45

要检查它是否不可见,我使用 !:

if ( !$('#book').is(':visible')) {
    alert('#book is not visible')
}

或者以下内容也是如此,将 jQuery 选择器保存在变量中,以便在多次需要时获得更好的性能:

var $book = $('#book')

if(!$book.is(':visible')) {
    alert('#book is not visible')
}

To check if it is not visible I use !:

if ( !$('#book').is(':visible')) {
    alert('#book is not visible')
}

Or the following is also the sam, saving the jQuery selector in a variable to have better performance when you need it multiple times:

var $book = $('#book')

if(!$book.is(':visible')) {
    alert('#book is not visible')
}
掌心的温暖 2024-07-14 01:08:45

使用类切换,而不是样式编辑。 。 。

使用指定用于“隐藏”元素的类很容易,也是最有效的方法之一。 使用 Display 样式“none”切换“隐藏”类将比直接编辑该样式执行得更快。 我在 Stack Overflow 问题中非常彻底地解释了其中的一些内容将同一 div 中的两个元素设置为可见/隐藏


JavaScript 最佳实践和优化

这是 Google 前端工程师 Nicholas Zakas 的一个真正具有启发性的 Google 技术讲座视频:

Use class toggling, not style editing . . .

Using classes designated for "hiding" elements is easy and also one of the most efficient methods. Toggling a class 'hidden' with a Display style of 'none' will perform faster than editing that style directly. I explained some of this pretty thoroughly in Stack Overflow question Turning two elements visible/hidden in the same div.


JavaScript Best Practices and Optimization

Here is a truly enlightening video of a Google Tech Talk by Google front-end engineer Nicholas Zakas:

满天都是小星星 2024-07-14 01:08:45
expect($("#message_div").css("display")).toBe("none");
expect($("#message_div").css("display")).toBe("none");
傾旎 2024-07-14 01:08:45

可以创建一个函数来检查可见性/显示属性,从而判断元素是否显示在 UI 中。

function checkUIElementVisible(element) {
    return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}

工作小提琴

A function can be created in order to check for visibility/display attributes in order to gauge whether the element is shown in the UI or not.

function checkUIElementVisible(element) {
    return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}

Working Fiddle

橘和柠 2024-07-14 01:08:45

但是如果元素的 CSS 如下所示怎么办?

.element{
    position: absolute;left:-9999;    
}

因此,还应该考虑这个 Stack Overflow 问题的答案如何检查元素是否在屏幕外

But what if the element's CSS is like the following?

.element{
    position: absolute;left:-9999;    
}

So this answer to Stack Overflow question How to check if an element is off-screen should also be considered.

人海汹涌 2024-07-14 01:08:45

您需要检查两者。 显示和可见性:

var $this = $(this)
if ($this.css("display") == "none" || $this.css("visibility") == "hidden") {
    // The element is not visible
} else {
    // The element is visible
}

如果我们检查 $this.is(":visible"),jQuery 会自动检查这两件事。

You need to check both. Display as well as visibility:

var $this = $(this)
if ($this.css("display") == "none" || $this.css("visibility") == "hidden") {
    // The element is not visible
} else {
    // The element is visible
}

If we check for $this.is(":visible"), jQuery checks for both the things automatically.

第七度阳光i 2024-07-14 01:08:45
$(document).ready(function() {
   var visible = $('#tElement').is(':visible');

   if(visible) {
      alert("visible");
                    // Code
   }
   else
   {
      alert("hidden");
   }
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<input type="text" id="tElement" style="display:block;">Firstname</input>

$(document).ready(function() {
   var visible = $('#tElement').is(':visible');

   if(visible) {
      alert("visible");
                    // Code
   }
   else
   {
      alert("hidden");
   }
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<input type="text" id="tElement" style="display:block;">Firstname</input>

多孤肩上扛 2024-07-14 01:08:45

只需通过检查布尔值来检查可见性,例如:

if (this.hidden === false) {
    // Your code
}

我为每个函数使用了此代码。 否则,您可以使用 is(':visible') 来检查元素的可见性。

Simply check visibility by checking for a boolean value, like:

if (this.hidden === false) {
    // Your code
}

I used this code for each function. Otherwise you can use is(':visible') for checking the visibility of an element.

再浓的妆也掩不了殇 2024-07-14 01:08:45

因为 具有visibility:hidden或opacity:0的元素被认为是可见的,因为它们仍然消耗布局中的空间(如jQuery :visible Selector) - 我们可以通过这种方式检查元素是否真的可见:

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

Because Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout (as described for jQuery :visible Selector) - we can check if element is really visible in this way:

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;
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文