如何在不使用插件的情况下检查视口中的哪个部分

How to check which section is in the viewport without the use of a plugin?

本文关键字:视口 检查 个部 情况下 插件      更新时间:2023-09-26

我正在创建一个包含多个部分的新网站。每个节都有一个标题,其中包含一个1标题(h1)。此外,每个部分都有一个id属性。

我正在寻找的是如何在每个部分的标题中添加最小视差效果。当节在视口中时,它应该从为标头的margin-top设置动画开始,例如x像素量,例如5或10px。

我想检查哪个部分在浏览器的视口中,如果是,请开始视差动画。如果可能的话,不需要任何插件。我该怎么做?

我想到了以下内容:

$(window).scroll(function() {
    // Get the offset of the window from the top of page
    var windowPos = $(window).scrollTop();
    $('.main').find('section').each(function() { 
        var anchorId = $(this);
        var target = $(anchorId.attr("id"));
        var offsetTop = target.position().top;
        if (offsetTop <= windowPos && offsetTop + target.height() > windowPos) {
            console.log(this);
            // Parallax function here
        }
    });

});

不幸的是,我收到错误:Uncaught TypeError: Cannot read property 'top' of undefined

因此,我希望代码返回部分的id,然后在视口中可见。然后开始动画该部分的标题。

提前谢谢。现场演示:http://codepen.io/anon/pen/xZwpzX?editors=101

您的this语句:

var target = $(anchorId.attr("id"));
var offsetTop = target.position().top;

应该是:

var target = $("#"+anchorId.attr("id"));
var offsetTop = target.offset().top;

由于anchorId.attr('id')将返回作为字符串的id,因此您需要为id预加#或为class预加.。此外,您在this中有元素,可以使用它。

试试这个,希望它能起作用:

function isElementInViewport (el) {
    //special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}
$(window).scroll(function() {
    $('.main').find('section').each(function() { 
        if (isElementInViewport($(this))) {
            console.log($(this));
            // Parallax function here
        }
    });
})

如何判断DOM元素在当前视口中是否可见?