jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在jquery中知道滚动条何时到达浏览器的中心?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如何知道浏览器何时到达浏览器的中心?当滚动条到达浏览器的中心而不是到达浏览器的末尾时,我需要加载内容.

解决方法

示例1 – 到达页面中间时加载内容

在滚动窗口时,使用jQuery .scroll()@L_197_4@事件来触发事件.

从那里你可以简单地使用.scrollTop()获取浏览器中与页面顶部相关的当前位置,同时使用.height()获取窗口的最大高度并除以2得到中心点.

一旦.scrollTop()通过中心点,你就找到了中间点.

$(window).scroll(function() {
    if ($(window).scrollTop()  > $(window).height() / 2)
    {
        // middle of page hit,load extra content here
        alert('You are in the middle of the page');

        // Uncomment out the line below to unbind the scroll event if the 
        // execution of this code is only desired once.
        // $(this).unbind('scroll');
    }
});

Fiddle Demo

示例2 – 当标识元素滚动到视图中时加载内容(这更类似于Facebook的工作方式,它们在页面上有一个“加载更多”元素,当它滚动到视图中时,意味着您到达内容的结尾并且装载更多.

您可以使用的另一种@L_197_4@是使用此功能

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

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

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

Scott Dowding在这个答案Check if element is visible after scrolling

可用于检测元素在浏览器查看区域内何时可见.使用这种@L_197_4@,您可以在页面底部/中间放置一个元素,并再次使用.scroll()在滚动时触发事件.

当该元素进入视图时,激活您的代码以加载更多内容或您想要做的任何事情.

$(window).scroll(function () {
    if (isScrolledIntoView($('#loadmorecontent')))
    {
        // element has been scrolled into view,load extra contents here
        alert('element scrolled into view');

        // Uncomment out the line below to unbind the scroll event if the 
        // execution of this code is only desired once.
        // $(this).unbind('scroll');
    }
});

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

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

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

Fiddle Demo

大佬总结

以上是大佬教程为你收集整理的如何在jquery中知道滚动条何时到达浏览器的中心?全部内容,希望文章能够帮你解决如何在jquery中知道滚动条何时到达浏览器的中心?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。