检查元素是否在视口中部分 [英] Check if element is partially in viewport

查看:45
本文介绍了检查元素是否在视口中部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定元素在视口中是部分还是完全.

I'm trying to determine if an element is partially or fully in the viewport.

我发现了这一点,它将确定元素是否完全可见,但是在尝试确定部分可见性时会感到困惑.我不想使用jQuery.

I've found this which will determine if an element is fully in view but kept getting confused when trying to determine partial visibility. I don't want to use jQuery.

基本上,这个想法是页面上会有一个可能看不见的元素.一旦用户将该元素滚动到视图中(甚至部分滚动),它就应该触发一个事件.我将通过绑定onscroll事件来处理事件触发器.我只需要检测即可正常工作.

Basically, the idea is that there will be an element on the page that could be out of view. Once the user scrolls that element into view, even partially, it should trigger an event. I'll handle the event trigger by binding an onscroll event. I just need the detection to work properly.

function isInViewport(element) {
    var rect = element.getBoundingClientRect();
    var html = document.documentElement;
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || html.clientHeight) &&
        rect.right <= (window.innerWidth || html.clientWidth)
    );
}

任何帮助将不胜感激!

推荐答案

最新答案,但是大约一个月前,我编写了一个函数来执行此操作,它确定在视口中以百分比表示的可见元素数量.Ive在iPhone/iPad上的Chrome,Firefox,IE11,iOS中对其进行了测试.当元素的X百分比(从0到100的数字)可见时,该函数返回true.仅确定元素的测量值是否可见,而不确定元素是否被不透明,可见性等隐藏.

Late answer, but about a month ago I wrote a function that does exactly that, it determines how much an element is visible measured in percent in the viewport. Ive tested it in chrome, firefox, ie11, ios on iphone/ipad. The function returns true when X percent (as a number from 0 to 100) of the element is visible. Only determines if the measurements of the element are visible and not if the element is hidden with opacity, visibility etc..

const isElementXPercentInViewport = function(el, percentVisible) {
  let
    rect = el.getBoundingClientRect(),
    windowHeight = (window.innerHeight || document.documentElement.clientHeight);

  return !(
    Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / +-rect.height) * 100)) < percentVisible ||
    Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible
  )
};

这篇关于检查元素是否在视口中部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆