[英]Check if element is visible for certain percentage on screen (viewport)?
如何檢測某些元素是否可見? 為了更好地了解下面的圖像。
我希望在圖像半可見時觸發事件。 如果它適用於所有瀏覽器和設備(平板電腦和智能手機),那就太棒了。
Jquery.fracs插件似乎完全符合您的需求。
function callback(fracs: Fractions, previousFracs: Fractions) {
if(fracs > 0.5)
doSomething();
};
var fracs = $("img").fracs(callback);
你的窗口在
$(document).scrollTop()
和
$(document).scrollTop() + $(window).height()
如果
$(element).offset().top
落在那些之間,它應該是可見的。
編輯:我假設您的元素(其可見性將被確定)絕對定位。 如果沒有,那將會有點復雜。
EDIT2:這僅用於確定垂直偏移情況下的可見性。 對於水平版本,將“scrollTop”替換為“scrollLeft”,將“height”替換為“width”,將“top”替換為“left”。
有一個巧妙的插件,專門為此目的編寫的jQuery壓縮文件。
您想要檢查項目是否可以從屏幕底部或頂部查看。 所以邏輯是這樣的:
on window scroll event
if item.y is less than scroll.y, calculate amount off screen
if item.y + item.height is greater than scroll.y + scroll.height, calculate amount off screen
deduct both values off the item.height to find the total off screen
create a percentage of this
所以在javascript中,這將是這樣的:
var el = document.getElementById('item1'),
rect = el.getBoundingClientRect(),
item = {
el: el,
x: rect.left,
y: rect.top,
w: el.offsetWidth,
h: el.offsetHeight
};
window.addEventListener('scroll', function (e) {
var deduct = 0,
percentage = 0,
x = window.pageXOffset,
y = window.pageYOffset,
w = window.innerWidth,
h = window.innerHeight;
if (item.y < y) {
deduct += (y - item.y);
}
if ((item.y + item.h) > (y + h)) {
deduct += (item.y + item.h) - (y + h);
}
if (deduct > item.h) {
deduct = item.h;
}
percentage = Math.round(((item.h - deduct) / item.h) * 100);
});
我已經排除了對舊瀏覽器的支持,但是如果你需要它,它將是:
x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft,
y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop,
w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var $w = $(window), wh = $w.height(),
top = $w.scrollTop(), bottom = top + wh,
$img = $("#image"),
imgCenter = $img.offset().top + $img.height()/2;
if (imgCenter >= top && imgCenter < bottom) {
// the image is half-visible
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.