检查元素在屏幕上是否可见特定百分比(视口)?

时间:2014-03-28 10:03:49

标签: javascript jquery

如何检测某些元素是否可见?为了更好地了解下面的图片,请看。

Screen with half-visible image

我希望在图像半可见时触发事件。如果它适用于所有浏览器和设备(平板电脑和智能手机),那就太棒了。

5 个答案:

答案 0 :(得分:9)

Jquery.fracs插件似乎完全符合您的需求。

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

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

答案 1 :(得分:3)

您的窗口位于

之间
$(document).scrollTop()

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

如果

$(element).offset().top

落在那些之间,它应该是可见的。

编辑:我假设您的元素(其可见性将被确定)绝对定位。如果没有,那就有点复杂了。

EDIT2:这仅用于确定垂直偏移的可见性。对于横向版本,请替换" scrollTop"用" scrollLeft"," height"用"宽度" " top"用"左"。

答案 2 :(得分:1)

有一个整洁的插件,jQuery fracs专门为此目的编写。

答案 3 :(得分:1)

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

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;

答案 4 :(得分: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
}
相关问题