though there is a visible property that you can test if a element is having the visibility set to true (display = none), however, it is more arguable why not just to test the offsetWidth and the offsetHeight property, thought it looks crude, but it shold be incredibly effecient in that if a width and height is 0, then even if the display is not none, you will not be able to see it on the screen.
however, there is one exception for the height and width test, it is because that IE has tr return width or height as 0; so we have the following code.
<html>
<head>
<title>Visibility Test</title>
<script type="text/javascript">
function isVisible(elem) {
var isTR = elem.nodeName.toLowerCase() === "tr",
w = elem.offsetWidth, h = elem.offsetHeight;
return w !== 0 && h !== 0 && !isTR ?
true :
w === 0 && h === 0 && !isTR ?
false :
computedStyle(elem, "display") === "none";
}
window.onload = function () {
var block = document.getElementById("block");
var none = document.getElementById("none");
// Alerts out 'true'
alert(isVisible(block));
// Alerts out 'false'
alert(isVisible(none));
};
</script>
</head>
<body>
<div id="block">Test</div>
<div id="none" style="display:none;">Test</div>
</body>
</html>
本文介绍了一种检测网页元素是否可见的方法。通过判断元素的宽度和高度是否为零,并考虑到IE浏览器的特殊情况,来确定元素是否真正可见。文章还提供了一个JavaScript函数示例,展示了如何实现这一功能。
1461

被折叠的 条评论
为什么被折叠?



