Javascript判断页面内元素是否可见的3种方法
判断网页中的Element元素是否可见,在Google上搜索得到3中方法:
var d = document.getElementById('someId');
1. d.checkVisibility();
截至 2023 年,Chrome 105+、Firefox 106+ 支持 checkVisibility(),当时 Safari 还不支持(后续版本已逐步支持,使用前请查最新兼容表)。
2. 判断d.offsetParent 是否为null。
if (d.offsetParent === null) { console.log(' the element currently is invisible'); }
原文连接:https://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom
3. 判断offsetWidth和offsetHeight同时等于0
function isvisible(obj) { return obj.offsetWidth > 0 && obj.offsetHeight > 0; }
这三种方法都只是“近似判断”:offsetParent/offsetWidth 对 position:fixed、visibility:hidden、opacity:0、被遮挡等情况并不完全等价于“用户看得见”。
这是来自 jQuery 的是否可见的实现
原文链接:https://stackoverflow.com/questions/4795473/check-visibility-of-an-element-with-javascript
浙公网安备 33010602011771号