使用 JavaScript 检查对象的可见性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4795473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:07:46  来源:igfitidea点击:

Check visibility of an object with JavaScript

javascripthtmlcss

提问by Denise

I have a variable called "object". How can I check with JavaScript if it is visible?

我有一个名为“对象”的变量。如果 JavaScript 可见,我如何检查它?

I tried !object.getAttribute("dislay", "none")... but that doesn't work.

我试过 !object.getAttribute("dislay", "none")... 但这不起作用。

Could somebody help me please?

有人可以帮我吗?

Thank you!

谢谢!

回答by Andrey

function isvisible(obj) {
  return obj.offsetWidth > 0 && obj.offsetHeight > 0;
}

as it's implemented in JQuery.

因为它是在 JQuery 中实现的。

回答by Arnaud Le Blanc

If you use jQuery, the following will return true if the object is visible:

如果您使用 jQuery,如果对象可见,以下内容将返回 true:

$(object).is(':visible');

If not, you can try these:

如果没有,你可以试试这些:

if (object.style['display'] != 'none')

But this will work only if display:nonehas been set explicitly on this object.

但这只有在display:none已在此对象上明确设置时才有效。

回答by vmg

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')

回答by u476945

To get value of a display style using javascript you can use:

要使用 javascript 获取显示样式的值,您可以使用:

IE:

IE:

document.getElementById('mydiv').currentStyle.display
or
object.currentStyle.display

Others:

其他:

document.getElementById('mydiv').getComputedStyle('display')
or
object.getComputedStyle('display')

回答by Kyle

Doesn't look like you're using the getAttribute method correctly. Try taking a look at this.

看起来您没有正确使用 getAttribute 方法。试着看看这个

回答by M.Nadeem Shaikh

Here is the working version: http://jsfiddle.net/PEA4j/

这是工作版本: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>