2014-03-28 44 views
8

如何检测某些元素是否可见?为了更好地了解下图,请仔细阅读。检查元素在屏幕(视口)上是否可见一定比例?

Screen with half-visible image

我想火的事件当图像是半可见。如果它适用于所有浏览器和设备(平板电脑和智能手机),那将会很棒。

+1

您的形象是否完全定位?另外,真棒头像! –

+0

是的,图像是绝对定位的。 – Manny

回答

9

Jquery.fracs插件似乎正是你所需要的。

function callback(fracs: Fractions, previousFracs: Fractions) { 
    if(fracs > 0.5) 
     doSomething(); 
}; 

var fracs = $("img").fracs(callback); 
+0

这就是我需要的!谢谢:) – Manny

+0

我已经用触发事件的代码更新了答案。虽然这可能是缓慢的。 –

+0

不幸的是,当用户放大和缩小时,这不适用于移动 –

3

你的窗口是

如果

之间
$(document).scrollTop() 

$(document).scrollTop() + $(window).height() 

$(element).offset().top 

那些介于,它应该是可见的。

编辑:我假设你的元素(其能见度是确定的)绝对定位。如果不是,那会更复杂一点。

编辑2:这只是为了确定垂直偏移情况下的可视性。对于水平版本,将“scrollTop”替换为“scrollLeft”,将“height”替换为“宽度”,将“顶部”替换为“左”。

0
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 
} 
+0

答案的一些解释会对此有所帮助 –

0

您想检查该项目是否可以从屏幕底部或顶部查看。这样的逻辑是这样的:

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; 
相关问题