javascript - trick to test visibility of an element

本文介绍了一种检测网页元素是否可见的方法。通过判断元素的宽度和高度是否为零,并考虑到IE浏览器的特殊情况,来确定元素是否真正可见。文章还提供了一个JavaScript函数示例,展示了如何实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值