ChatGPT解决这个技术问题 Extra ChatGPT

如何检查滚动后元素是否可见?

我正在通过 AJAX 加载元素。其中一些只有在您向下滚动页面时才可见。有什么方法可以知道元素现在是否在页面的可见部分中?

他的意思是他想要一种方法来知道给定元素是否显示在浏览器窗口中,或者用户是否需要滚动才能看到它。
要检查一个元素是否在容器中完全可见,只需添加一个额外的选择器参数并重新使用它的 elem 代码。 Library.IsElementVisibleInContainer = function (elementSelector, containerSelector) { var containerViewTop = $(containerSelector).offset().top; var containerViewBottom = containerViewTop + $(containerSelector).height();
所有答案都会触发重排,所以它可能是瓶颈,如果支持,你喊使用 IntersectionObserver。在现代浏览器上会有更好的性能,

A
Andrea Casaccia

这应该可以解决问题:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

简单的实用函数 这将允许您调用一个实用函数,该函数接受您正在寻找的元素,以及您希望该元素是完全可见还是部分可见。

function Utils() {

}

Utils.prototype = {
    constructor: Utils,
    isElementInView: function (element, fullyInView) {
        var pageTop = $(window).scrollTop();
        var pageBottom = pageTop + $(window).height();
        var elementTop = $(element).offset().top;
        var elementBottom = elementTop + $(element).height();

        if (fullyInView === true) {
            return ((pageTop < elementTop) && (pageBottom > elementBottom));
        } else {
            return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
        }
    }
};

var Utils = new Utils();

用法

var isElementInView = Utils.isElementInView($('#flyout-left-container'), false);

if (isElementInView) {
    console.log('in view');
} else {
    console.log('out of view');
}

请注意,这仅在文档是正在滚动的元素时才有效,即您没有检查滚动内部窗格中某些元素的可见性。
对于:“视图中元素的任何部分”,我使用: ((( elemTop >= docViewTop) && (elemTop <= docViewBottom)) || ((elemBottom >= docViewTop) && (elemBottom <= docViewBottom)))
当元素在打开的文档中时,这工作正常,当用于某些可滚动分区内的元素时,这会产生不适当的结果,我尝试用 $("somediv") 替换 $(window) 仍然没有准确的结果,我怎样才能得到准确的结果?
j
jcubic

This answer 原版:

function isScrolledIntoView(el) {
    var rect = el.getBoundingClientRect();
    var elemTop = rect.top;
    var elemBottom = rect.bottom;

    // Only completely visible elements return true:
    var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
    // Partially visible elements return true:
    //isVisible = elemTop < window.innerHeight && elemBottom >= 0;
    return isVisible;
}

这不应该是 isVisible = elementTop < window.innerHeight && elementBottom >= 0 吗?否则屏幕上的一半元素返回 false。
不。我检查某些元素是否在页面上完全可见。如果您想检查某些部分的可见性 - 您可以自定义此代码段。
我发现这个答案比选择的答案表现更好。也更简单。
与批准的答案相比,这对数百个元素的表现要好得多。
J
Joe Lencioni

更新:使用 IntersectionObserver

到目前为止,我发现的最佳方法是 jQuery appear plugin。奇迹般有效。

模仿自定义的“出现”事件,当元素滚动到视图中或以其他方式对用户可见时触发。 $('#foo').appear(function() { $(this).text('Hello world'); });此插件可用于防止对隐藏或可见区域之外的内容的不必要请求。


毫无疑问,这是一个很酷的插件,但没有回答问题。
有没有消失插件?
D
Devs love ZenUML

使用 IntersectionObserver API

(在现代浏览器中原生)

使用观察者可以轻松高效地确定元素是否在视口或任何可滚动容器中可见。

无需附加 scroll 事件并手动检查事件回调,这样效率更高:

// 定义一个观察者实例 var observer = new IntersectionObserver(onIntersection, { root: null, // 默认是视口阈值:0.5 // 目标可见区域的百分比。触发器 "onIntersection" }) // 在交叉点调用回调change function onIntersection(entries, opts){ entries.forEach(entry => entry.target.classList.toggle('visible', entry.isIntersecting) ) } // 使用观察者观察一个元素 observer.observe( document.querySelector ('.box') ) // 停止观察: //observer.unobserve(entry.target) span{ position:fixed;顶部:0;左:0; } .box{ 宽度:100px;高度:100px;背景:红色;边距:1000px;过渡:.75s; } .box.visible{ 背景:绿色;边界半径:50%; } 垂直滚动 &水平...

现代浏览器支持,包括移动浏览器。 IE 中不支持 - 查看浏览器支持表


Safari 是新的 IE,所有常青浏览器都支持我这些天想要实现的一切......除了 safari
A
Ally

这是我的纯 JavaScript 解决方案,如果它也隐藏在可滚动容器中,它也可以工作。

Demo here(也尝试调整窗口大小)

var visibleY = function(el){
  var rect = el.getBoundingClientRect(), top = rect.top, height = rect.height, 
    el = el.parentNode
  // Check if bottom of the element is off the page
  if (rect.bottom < 0) return false
  // Check its within the document viewport
  if (top > document.documentElement.clientHeight) return false
  do {
    rect = el.getBoundingClientRect()
    if (top <= rect.bottom === false) return false
    // Check if the element is out of view due to a container scrolling
    if ((top + height) <= rect.top) return false
    el = el.parentNode
  } while (el != document.body)
  return true
};

编辑 2016-03-26:我已经更新了解决方案以考虑滚动过去的元素,因此它隐藏在可滚动容器的顶部上方。编辑 2018-10-08:更新为在屏幕上方滚动出视图时处理。


+1这是考虑到元素递归性质的唯一编码(即不是第三方)答案。我已扩展为处理水平、垂直和页面滚动:jsfiddle.net/9nuqpgqa
此处的 Angular 版本:stackblitz.com/edit/angular-ivy-hsnnia - 包括识别表的哪些行是可见的。
@Pebbl 的解决方案非常有用,但不考虑带有 overflow: auto 的元素
K
K-Gun

普通香草检查元素 (el) 在可滚动 div (holder) 中是否可见

function isElementVisible (el, holder) {
  holder = holder || document.body
  const { top, bottom, height } = el.getBoundingClientRect()
  const holderRect = holder.getBoundingClientRect()

  return top <= holderRect.top
    ? holderRect.top - top <= height
    : bottom - holderRect.bottom <= height
}

与 jQuery 一起使用:

var el = $('tr:last').get(0);
var holder = $('table').get(0);
var isVisible = isScrolledIntoView(el, holder);

在这个单页应用程序的时代,检查一个元素是否在除 window 之外的其他元素中可见已变得越来越普遍。这就是为什么这个得到我的赞成。
注意:如果您想根据元素的任何不可见部分(如我的情况)来返回此值,请从函数中删除 height 变量并将其使用的位置更改为仅 0(零)。然后,如果您只隐藏了元素的“部分”,它将返回 false。
为什么你在 jQuery 用法中的函数名不一样?
F
Fedir RYKHTIK

jQuery Waypoints 插件在这里非常好用。

$('.entry').waypoint(function() {
   alert('You have scrolled to an entry.');
});

site of the plugin 上有一些示例。


对我来说,它只适用于偏移量 $('#my-div').waypoint(function() { console.log('Hello there!'); }, { offset: '100%' });
s
sectus

怎么样

function isInView(elem){
   return $(elem).offset().top - $(window).scrollTop() < $(elem).height() ;
}

之后,一旦元素出现在这样的视图中,您就可以触发任何您想要的东西

$(window).scroll(function(){
   if (isInView($('.classOfDivToCheck')))
      //fire whatever you what 
      dothis();
})

这对我来说很好


S
Snigdha Batra

Tweeked Scott Dowding 为我的要求提供的很酷的功能 - 这用于查找元素是否刚刚滚动到屏幕中,即它的顶部边缘。

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}

S
Sampson

WebResourcesDepot 写了 a script to load while scrolling 使用 jQuery 前一段时间。您可以查看他们的Live Demo Here。他们的功能的牛肉是这样的:

$(window).scroll(function(){
  if  ($(window).scrollTop() == $(document).height() - $(window).height()){
    lastAddedLiveFunc();
  }
});

function lastAddedLiveFunc() { 
  $('div#lastPostsLoader').html('<img src="images/bigLoader.gif">');
  $.post("default.asp?action=getLastPosts&lastPostID="+$(".wrdLatest:last").attr("id"),
    function(data){
        if (data != "") {
          $(".wrdLatest:last").after(data);         
        }
      $('div#lastPostsLoader').empty();
    });
};

D
Domysee

这里的大多数答案都没有考虑到一个元素也可以被隐藏,因为它被滚动到一个 div 的视图之外,而不仅仅是整个页面。

为了覆盖这种可能性,您基本上必须检查元素是否位于每个父元素的边界内。

该解决方案正是这样做的:

function(element, percentX, percentY){
    var tolerance = 0.01;   //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals
    if(percentX == null){
        percentX = 100;
    }
    if(percentY == null){
        percentY = 100;
    }

    var elementRect = element.getBoundingClientRect();
    var parentRects = [];

    while(element.parentElement != null){
        parentRects.push(element.parentElement.getBoundingClientRect());
        element = element.parentElement;
    }

    var visibleInAllParents = parentRects.every(function(parentRect){
        var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);
        var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);
        var visiblePercentageX = visiblePixelX / elementRect.width * 100;
        var visiblePercentageY = visiblePixelY / elementRect.height * 100;
        return visiblePercentageX + tolerance > percentX && visiblePercentageY + tolerance > percentY;
    });
    return visibleInAllParents;
};

它还允许您指定它必须在每个方向上可见的百分比。
它不包括它可能由于其他因素(例如 display: hidden)而被隐藏的可能性。

这应该适用于所有主要浏览器,因为它只使用 getBoundingClientRect。我亲自在 Chrome 和 Internet Explorer 11 中对其进行了测试。


感谢您提供此代码。我想知道如果您有多个嵌套的可滚动元素,您将如何在滚动上添加事件侦听器?似乎仅仅将监听器添加到窗口是不够的,我们是否必须遍历到顶部父级才能将监听器添加到每个可滚动容器?
@mr1031011 应该可以将处理程序添加到窗口,然后检查目标以识别滚动的容器。
对,它不适用于@vanowm 给出的示例,
这通过视口下方的按钮失败了最简单的测试,错误地将按钮报告为可见:jsfiddle - 请参阅小提琴的控制台。或者这是在现实中不会发生的某种 jsfiddle iframe 限制?它也不能正确处理 <html style="overflow: hidden auto; height: 100%;,这是 jQuery UI 布局插件所做的。
R
Robert

isScrolledIntoView 是一个非常需要的功能,所以我试了一下,它适用于不高于视口的元素,但如果元素比视口大,它就不起作用。要解决此问题,请轻松更改条件

return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));

对此:

return (docViewBottom >= elemTop && docViewTop <= elemBottom);

在此处查看演示:http://jsfiddle.net/RRSmQ/


B
Brent Barbata

这会考虑元素具有的任何填充、边框或边距,以及大于视口本身的元素。

function inViewport($ele) {
    var lBound = $(window).scrollTop(),
        uBound = lBound + $(window).height(),
        top = $ele.offset().top,
        bottom = top + $ele.outerHeight(true);

    return (top > lBound && top < uBound)
        || (bottom > lBound && bottom < uBound)
        || (lBound >= top && lBound <= bottom)
        || (uBound >= top && uBound <= bottom);
}

要调用它,请使用以下内容:

var $myElement = $('#my-element'),
    canUserSeeIt = inViewport($myElement);

console.log(canUserSeeIt); // true, if element is visible; false otherwise

A
Adrian P.

这是另一个解决方案:

<script type="text/javascript">
$.fn.is_on_screen = function(){
    var win = $(window);
    var viewport = {
        top : win.scrollTop(),
        left : win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right ||    viewport.bottom < bounds.top || viewport.top > bounds.bottom));
 };

if( $('.target').length > 0 ) { // if target element exists in DOM
    if( $('.target').is_on_screen() ) { // if target element is visible on screen after DOM loaded
        $('.log').html('<div class="alert alert-success">target element is visible on screen</div>'); // log info       
    } else {
        $('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
    }
}
$(window).on('scroll', function(){ // bind window scroll event
if( $('.target').length > 0 ) { // if target element exists in DOM
    if( $('.target').is_on_screen() ) { // if target element is visible on screen after DOM loaded
        $('.log').html('<div class="alert alert-success">target element is visible on screen</div>'); // log info
    } else {
        $('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
    }
}
});
</script>

JSFiddle 中查看


P
Pascal Gagneur
function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop(),
        docViewBottom = docViewTop + $(window).height(),
        elemTop = $(elem).offset().top,
     elemBottom = elemTop + $(elem).height();
   //Is more than half of the element visible
   return ((elemTop + ((elemBottom - elemTop)/2)) >= docViewTop && ((elemTop + ((elemBottom - elemTop)/2)) <= docViewBottom));
}

B
Brett Zamir

我需要检查可滚动 DIV 容器内元素的可见性

    //p = DIV container scrollable
    //e = element
    function visible_in_container(p, e) {
        var z = p.getBoundingClientRect();
        var r = e.getBoundingClientRect();

        // Check style visiblilty and off-limits
        return e.style.opacity > 0 && e.style.display !== 'none' &&
               e.style.visibility !== 'hidden' &&
               !(r.top > z.bottom || r.bottom < z.top ||
                 r.left > z.right || r.right < z.left);
    }

C
Community

this great answer 的基础上,您可以使用 ES2015+ 进一步简化它:

function isScrolledIntoView(el) {
  const { top, bottom } = el.getBoundingClientRect()
  return top >= 0 && bottom <= window.innerHeight
}

如果您不关心顶部超出窗口而只关心底部已被查看,则可以将其简化为

function isSeen(el) {
  return el.getBoundingClientRect().bottom <= window.innerHeight
}

甚至是单线

const isSeen = el => el.getBoundingClientRect().bottom <= window.innerHeight

n
ness-EE

有一个 plugin for jQuery called inview 添加了一个新的“inview”事件。

下面是一些不使用事件的 jQuery 插件的代码:

$.extend($.expr[':'],{
    inView: function(a) {
        var st = (document.documentElement.scrollTop || document.body.scrollTop),
            ot = $(a).offset().top,
            wh = (window.innerHeight && window.innerHeight < $(window).height()) ? window.innerHeight : $(window).height();
        return ot > st && ($(a).height() + ot) < (st + wh);
    }
});

(function( $ ) {
    $.fn.inView = function() {
        var st = (document.documentElement.scrollTop || document.body.scrollTop),
        ot = $(this).offset().top,
        wh = (window.innerHeight && window.innerHeight < $(window).height()) ? window.innerHeight : $(window).height();

        return ot > st && ($(this).height() + ot) < (st + wh);
    };
})( jQuery );

我在一个叫 James 的家伙的评论 (http://remysharp.com/2009/01/26/element-in-view-event-plugin/) 中发现了这一点


M
Manash Kumar

我为此找到的最简单的解决方案是 Intersection Observer API:

var observer = new IntersectionObserver(function(entries) {
    if(entries[0].isIntersecting === true)
        console.log('Element has just become visible in screen');
}, { threshold: [0] });

observer.observe(document.querySelector("#main-container"));

R
Romain Linsolas

我的应用程序中有这样一个方法,但它不使用 jQuery:

/* Get the TOP position of a given element. */
function getPositionTop(element){
    var offset = 0;
    while(element) {
        offset += element["offsetTop"];
        element = element.offsetParent;
    }
    return offset;
}

/* Is a given element is visible or not? */
function isElementVisible(eltId) {
    var elt = document.getElementById(eltId);
    if (!elt) {
        // Element not found.
        return false;
    }
    // Get the top and bottom position of the given element.
    var posTop = getPositionTop(elt);
    var posBottom = posTop + elt.offsetHeight;
    // Get the top and bottom position of the *visible* part of the window.
    var visibleTop = document.body.scrollTop;
    var visibleBottom = visibleTop + document.documentElement.offsetHeight;
    return ((posBottom >= visibleTop) && (posTop <= visibleBottom));
}

编辑:此方法适用于 IE(至少版本 6)。阅读评论以了解与 FF 的兼容性。


S
Samiya Akhtar

如果你想调整它以在另一个 div 中滚动项目,

function isScrolledIntoView (elem, divID) 

{

    var docViewTop = $('#' + divID).scrollTop();


    var docViewBottom = docViewTop + $('#' + divID).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); 
}

V
Vasuki Dileep

您可以使用 jquery 插件“onScreen”来检查滚动时元素是否在当前视口中。 The plugin sets the ":onScreen" of the selector to true when the selector appears on the screen.这是您可以包含在项目中的插件的链接。 “http://benpickles.github.io/onScreen/jquery.onscreen.min.js

您可以尝试以下对我有用的示例。

$(document).scroll(function() {
    if($("#div2").is(':onScreen')) {
        console.log("Element appeared on Screen");
        //do all your stuffs here when element is visible.
    }
    else {
        console.log("Element not on Screen");
        //do all your stuffs here when element is not visible.
    }
});

HTML 代码:

<div id="div1" style="width: 400px; height: 1000px; padding-top: 20px; position: relative; top: 45px"></div> <br>
<hr /> <br>
<div id="div2" style="width: 400px; height: 200px"></div>

CSS:

#div1 {
    background-color: red;
}
#div2 {
    background-color: green;
}

C
Community

一个基于 this answer 的示例,用于检查元素是否 75% 可见(即,不到 25% 的元素不在屏幕上)。

function isScrolledIntoView(el) {
  // check for 75% visible
  var percentVisible = 0.75;
  var elemTop = el.getBoundingClientRect().top;
  var elemBottom = el.getBoundingClientRect().bottom;
  var elemHeight = el.getBoundingClientRect().height;
  var overhang = elemHeight * (1 - percentVisible);

  var isVisible = (elemTop >= -overhang) && (elemBottom <= window.innerHeight + overhang);
  return isVisible;
}

J
John Doherty

this answer 的更高效版本:

 /**
 * Is element within visible region of a scrollable container
 * @param {HTMLElement} el - element to test
 * @returns {boolean} true if within visible region, otherwise false
 */
 function isScrolledIntoView(el) {
      var rect = el.getBoundingClientRect();
      return (rect.top >= 0) && (rect.bottom <= window.innerHeight);
 }

f
fatemeh kazemi

Javascript代码可以写成:

window.addEventListener('scroll', function() { var element = document.querySelector('#main-container'); var position = element.getBoundingClientRect(); // 检查是否完全可见 if(position.top >= 0 && position.bottom <= window.innerHeight) { console.log('元素在屏幕中完全可见'); } // 检查部分可见性 if(position.top < window.innerHeight && position.bottom >= 0) { console.log('元素在屏幕中部分可见'); } });

并在 react js 中写成:

componentDidMount() { window.addEventListener('scroll', this.isScrolledIntoView); } componentWillUnmount() { window.removeEventListener('scroll', this.isScrolledIntoView); } isScrolledIntoView() { var element = document.querySelector('.element'); var position = element.getBoundingClientRect(); // 检查是否完全可见 if (position.top >= 0 && position.bottom <= window.innerHeight) { console.log('元素在屏幕中完全可见'); } // 检查部分可见性 if (position.top < window.innerHeight && position.bottom >= 0) { console.log('元素在屏幕中部分可见'); } }


e
evanmcd

修改了接受的答案,以便元素必须将其显示属性设置为“无”以外的其他值,以使质量可见。

function isScrolledIntoView(elem) {
   var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();
  var elemDisplayNotNone = $(elem).css("display") !== "none";

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop) && elemDisplayNotNone);
}

b
bmlkc

这是一种使用 Mootools 在水平、垂直或两者中实现相同目标的方法。

Element.implement({
inVerticalView: function (full) {
    if (typeOf(full) === "null") {
        full = true;
    }

    if (this.getStyle('display') === 'none') {
        return false;
    }

    // Window Size and Scroll
    var windowScroll = window.getScroll();
    var windowSize = window.getSize();
    // Element Size and Scroll
    var elementPosition = this.getPosition();
    var elementSize = this.getSize();

    // Calculation Variables
    var docViewTop = windowScroll.y;
    var docViewBottom = docViewTop + windowSize.y;
    var elemTop = elementPosition.y;
    var elemBottom = elemTop + elementSize.y;

    if (full) {
        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
            && (elemBottom <= docViewBottom) && (elemTop >= docViewTop) );
    } else {
        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }
},
inHorizontalView: function(full) {
    if (typeOf(full) === "null") {
        full = true;
    }

    if (this.getStyle('display') === 'none') {
        return false;
    }

    // Window Size and Scroll
    var windowScroll = window.getScroll();
    var windowSize = window.getSize();
    // Element Size and Scroll
    var elementPosition = this.getPosition();
    var elementSize = this.getSize();

    // Calculation Variables
    var docViewLeft = windowScroll.x;
    var docViewRight = docViewLeft + windowSize.x;
    var elemLeft = elementPosition.x;
    var elemRight = elemLeft + elementSize.x;

    if (full) {
        return ((elemRight >= docViewLeft) && (elemLeft <= docViewRight)
            && (elemRight <= docViewRight) && (elemLeft >= docViewLeft) );
    } else {
        return ((elemRight <= docViewRight) && (elemLeft >= docViewLeft));
    }
},
inView: function(full) {
    return this.inHorizontalView(full) && this.inVerticalView(full);
}});

R
Rafael Garcia

如果元素的任何部分在页面上可见,此方法将返回 true。它在我的情况下效果更好,可能会帮助其他人。

function isOnScreen(element) {
  var elementOffsetTop = element.offset().top;
  var elementHeight = element.height();

  var screenScrollTop = $(window).scrollTop();
  var screenHeight = $(window).height();

  var scrollIsAboveElement = elementOffsetTop + elementHeight - screenScrollTop >= 0;
  var elementIsVisibleOnScreen = screenScrollTop + screenHeight - elementOffsetTop >= 0;

  return scrollIsAboveElement && elementIsVisibleOnScreen;
}

A
Adam Pietrasiak

我更喜欢使用 jQuery expr

jQuery.extend(jQuery.expr[':'], {  
    inview: function (elem) {
        var t = $(elem);
        var offset = t.offset();
        var win = $(window); 
        var winST = win.scrollTop();
        var elHeight = t.outerHeight(true);

        if ( offset.top > winST - elHeight && offset.top < winST + elHeight + win.height()) {
            return true;    
        }    
        return false;  
    }
});

所以你可以这样使用它

$(".my-elem:inview"); //returns only element that is in view
$(".my-elem").is(":inview"); //check if element is in view
$(".my-elem:inview").length; //check how many elements are in view

您可以在 scroll 事件函数等中轻松添加此类代码,以便在每次用户滚动视图时检查它。


W
WebWanderer

这个问题有 30 多个答案,但没有一个使用我一直在使用的极其简单的纯 JS 解决方案。没有必要仅仅为了解决这个问题而加载 jQuery,因为许多其他人都在推动。

为了判断元素是否在视口内,我们必须首先确定元素在主体内的位置。我们不需要像我曾经认为的那样递归地执行此操作。相反,我们可以使用 element.getBoundingClientRect()

pos = elem.getBoundingClientRect().top - document.body.getBoundingClientRect().top;

该值是对象顶部和主体顶部之间的 Y 差。

然后我们必须判断该元素是否在视野范围内。大多数实现都会询问整个元素是否在视口内,所以这就是我们要介绍的内容。

首先,窗口的顶部位置是:window.scrollY

我们可以通过将窗口的高度添加到其顶部位置来获得窗口的底部位置:

var window_bottom_position = window.scrollY + window.innerHeight;

让我们创建一个简单的函数来获取元素的顶部位置:

function getElementWindowTop(elem){
    return elem && typeof elem.getBoundingClientRect === 'function' ? elem.getBoundingClientRect().top - document.body.getBoundingClientRect().top : 0;
}

此函数将返回元素在窗口中的顶部位置,或者如果您使用 .getBoundingClientRect() 方法向它传递的元素不是元素,它将返回 0。这种方法已经存在了很长时间,因此您不必担心您的浏览器不支持它。

现在,我们元素的顶部位置是:

var element_top_position = getElementWindowTop(element);

And or 元素的底部位置是:

var element_bottom_position = element_top_position + element.clientHeight;

现在我们可以通过检查元素的底部位置是否低于视口的顶部位置以及检查元素的顶部位置是否高于视口的底部位置来确定元素是否在视口内:

if(element_bottom_position >= window.scrollY 
&& element_top_position <= window_bottom_position){
    //element is in view
else
    //element is not in view

从那里,您可以执行在元素上添加或删除 in-view 类的逻辑,然后您可以稍后在 CSS 中使用过渡效果进行处理。

我非常惊讶我在其他任何地方都没有找到这个解决方案,但我相信这是最干净、最有效的解决方案,而且它不需要您加载 jQuery!