用 getBoundingClientRect() 效能會比較好,直接參考 code:
狀況一:只要有一部超出畫面就偵測已在畫面外
var myElement = document.getElementById('my-element');
var bounding = myElement.getBoundingClientRect();
if (bounding.top >= 0 && bounding.left >= 0 && bounding.right <= window.innerWidth && bounding.bottom <= window.innerHeight) {
console.log('Element is in the viewport!');
} else {
console.log('Element is NOT in the viewport!');
}
狀況二:全部都在外面才判斷在畫面外
var myElement = document.getElementById('my-element');
var bounding = myElement.getBoundingClientRect();
var myElementHeight = myElement.offsetHeight;
var myElementWidth = myElement.offsetWidth;
function elementInViewport() {
var bounding = myElement.getBoundingClientRect();
if (bounding.top >= -myElementHeight
&& bounding.left >= -myElementWidth
&& bounding.right <= (window.innerWidth || document.documentElement.clientWidth) + myElementWidth
&& bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) + myElementHeight) {
console.log('Element is in the viewport!');
} else {
console.log('Element is NOT in the viewport!');
}
}
原始文章:
Check If Element Is Inside Of The Viewport With JavaScript