该方法的主要原理是getBoundingClientRect,之前也曾多次遇到相关场景。这里是优化框架时想到的,总结一下,代码如下:
1 // 判断元素在视口 2 function isInViewport(element) { 3 var rect = element.getBoundingClientRect(); 4 var html = document.documentElement; 5 var top = document.documentElement.clientTop; // 非IE为0,IE为2 6 var left= document.documentElement.clientLeft; 7 8 return ( 9 rect.top -top >= 0 && 10 rect.left -left >= 0 && 11 rect.bottom -top <= (window.innerHeight || html.clientHeight) && 12 rect.right -left <= (window.innerWidth || html.clientWidth) 13 ); 14 } 15 // isInViewport($("#addAddrAddControlId8Inp")[0])