繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM