Check visibility of an object with JavaScript
I have a variable called "object". How c开发者_开发百科an I check with JavaScript if it is visible?
I tried !object.getAttribute("dislay", "none")... but that doesn't work.
Could somebody help me please?
Thank you!
function isvisible(obj) {
return obj.offsetWidth > 0 && obj.offsetHeight > 0;
}
as it's implemented in JQuery.
If you use jQuery, the following will return true if the object is visible:
$(object).is(':visible');
If not, you can try these:
if (object.style['display'] != 'none')
But this will work only if display:none
has been set explicitly on this object.
To get value of a display style using javascript you can use:
IE:
document.getElementById('mydiv').currentStyle.display
or
object.currentStyle.display
Others:
document.getElementById('mydiv').getComputedStyle('display')
or
object.getComputedStyle('display')
if (object.style.visibility <> 'visible' || object.style.display == 'none')
If it doesn't work, try to use
if (object.currentStyle.visibility <> 'visible' || object.currentStyle.display == 'none')
Doesn't look like you're using the getAttribute method correctly. Try taking a look at this.
Here is the working version: http://jsfiddle.net/PEA4j/
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
alert("Is #foo1 visible: " + $("#foo1").is(":visible") + "\nIs #foo2 visible: " + $("#foo2").is(":visible"));
});
</script>
</head>
<body>
<div id="foo1" style="display:none">foo1 display none</div>
<div id="foo2">foo2 no display property;</div>
</body>
</html>
精彩评论