如何在没有jquery的情况下使用javascript进行无限滚动 [英] How to do infinite scrolling with javascript only without jquery

查看:89
本文介绍了如何在没有jquery的情况下使用javascript进行无限滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用javascript和jquery实现无限滚动。

I wish to implement infinite scrolling with javascript and without jquery.

我是javascript的新手。

I am new to javascript.

在网上搜索后,我有这个代码。

After searching all over the net, I have this code.

<!DOCTYPE html><html lang="en"><head><title>scrolling</title>
<style>
.page {height: 900px;border:solid 1px #ccc}
</style>
</head>
<body>

<div id="scrollcontent">

<div class="page"></div>

</div>

<script>

//########################
function getScrollXY() {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
}

function getDocHeight() {
var D = document;
return Math.max(
    D.body.scrollHeight, D.documentElement.scrollHeight,
    D.body.offsetHeight, D.documentElement.offsetHeight,
    D.body.clientHeight, D.documentElement.clientHeight
);
}

document.addEventListener("scroll", function (event) {
if (getDocHeight() == getScrollXY()[1] + window.innerHeight) 
{ 
  var oldcontent = document.getElementById('scrollcontent');
  oldcontent.innerHTML = oldcontent.innerHTML + '<div class="page">new content loaded</div>';
  document.getElementById("scrollcontent").innerHTML=oldcontent.innerHTML;

}
});
</script>
</body>
</html>

但是,此代码仅在滚动条触及底部时有效。

However, this code works only when the scrollbar touches the bottom.

我希望当用户距离底部100像素时它可以工作。 (或靠近底部)

I wish it to work when the user is 100 pixels from the bottom. (or near the bottom)

我还需要在大多数现代浏览器,移动设备等中使用该代码。

I also need the code to work in most of the modern browsers, mobile devices etc.

另外,有没有办法改进这段代码?请建议。

Also, is there any way to improve this code? Please suggest.

如果代码中有任何错误,请更正。

If there are any errors in the code, please correct.

谢谢

推荐答案

如何更换这行代码:

if (getDocHeight() == getScrollXY()[1] + window.innerHeight)

使用以下内容:

if (getDocHeight() - 20 <= getScrollXY()[1] + window.innerHeight) 

其中 20 是多少 px 从底部你想要触发器执行。

Where 20 is the number how much pxs from bottom you want the trigger to execute.

小提琴

Fiddle

这篇关于如何在没有jquery的情况下使用javascript进行无限滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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