Finding if element is visible (JavaScript )

 ̄綄美尐妖づ 提交于 2019-12-03 06:27:03

Display is not an attribute, it's a CSS property inside the style attribute.

You may be looking for

var myvar = document.getElementById("mydivID").style.display;

or

var myvar = $("#mydivID").css('display');

Try like this:

$(function () {
    // Handler for .ready() called.
    if ($("#mydivID").is(":visible")) {
        alert('Element is visible');
    }
});

FIDDLE

Please make sure to include the jQuery file inside the head tag, as follows

<head>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
Gaurav

If you would like to do this only javascript way you may try

window.getComputedStyle(document.getElementById("mydivID"),null).getPropertyValue('display')

Let's take a second to see what .is(":visible") is doing in jQuery, shall we?

Here's a link: https://github.com/jquery/jquery/blob/master/src/css.js#L529

return !jQuery.expr.filters.hidden( elem );

where

jQuery.expr.filters.hidden = function( elem ) {
    // Support: Opera <= 12.12
    // Opera reports offsetWidths and offsetHeights less than zero on some elements
    return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};

So, it's just checking the offset width and height of the element.

That said, and also worth noting, when jQuery checks to see if an element is hidden (i.e. like when triggering a 'toggle' event), it performs a check on the display property and its existence in the dom. https://github.com/jquery/jquery/blob/master/src/css.js#L43

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!