如何用纯 JavaScript 实现无限滚动

发布于 2024-11-16 15:15:29 字数 88 浏览 7 评论 0原文

我想避免使用 jQuery 或其他库,以保持代码最少,我需要的功能很少,我只想在用户滚动到底部时附加到列表。我该如何用普通的 Javascript 来做到这一点?

I want to avoid using jQuery or another library for the sake of keeping my code minimal, I need very little in the way of features, I just want to append to a list when the user scrolls to the bottom. How would I do this in plain Javascript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

真心难拥有 2024-11-23 15:15:29

基本上你只需要挂钩事件滚动,检查用户是否向下滚动足够,如果是的话添加一些内容:

<html><body>
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
  <div id="content"> </div>
</div>

<script language="JavaScript">
  // we will add this content, replace for anything you want to add
  var more = '<div style="height: 1000px; background: #EEE;"></div>';

  var wrapper = document.getElementById("wrapper");
  var content = document.getElementById("content");
  var test = document.getElementById("test");
  content.innerHTML = more;

  // cross browser addEvent, today you can safely use just addEventListener
  function addEvent(obj,ev,fn) {
    if(obj.addEventListener) obj.addEventListener(ev,fn,false);
    else if(obj.attachEvent) obj.attachEvent("on"+ev,fn);    
  }

  // this is the scroll event handler
  function scroller() {
    // print relevant scroll info
    test.innerHTML = wrapper.scrollTop+"+"+wrapper.offsetHeight+"+100>"+content.offsetHeight;

    // add more contents if user scrolled down enough
    if(wrapper.scrollTop+wrapper.offsetHeight+100>content.offsetHeight) {
      content.innerHTML+= more;
    }
  }

  // hook the scroll handler to scroll event
  addEvent(wrapper,"scroll",scroller);
</script>
</body></html>

Basicaly you just need to hook the event scroll, check if the user scrolled down enough and add some content if so:

<html><body>
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
  <div id="content"> </div>
</div>

<script language="JavaScript">
  // we will add this content, replace for anything you want to add
  var more = '<div style="height: 1000px; background: #EEE;"></div>';

  var wrapper = document.getElementById("wrapper");
  var content = document.getElementById("content");
  var test = document.getElementById("test");
  content.innerHTML = more;

  // cross browser addEvent, today you can safely use just addEventListener
  function addEvent(obj,ev,fn) {
    if(obj.addEventListener) obj.addEventListener(ev,fn,false);
    else if(obj.attachEvent) obj.attachEvent("on"+ev,fn);    
  }

  // this is the scroll event handler
  function scroller() {
    // print relevant scroll info
    test.innerHTML = wrapper.scrollTop+"+"+wrapper.offsetHeight+"+100>"+content.offsetHeight;

    // add more contents if user scrolled down enough
    if(wrapper.scrollTop+wrapper.offsetHeight+100>content.offsetHeight) {
      content.innerHTML+= more;
    }
  }

  // hook the scroll handler to scroll event
  addEvent(wrapper,"scroll",scroller);
</script>
</body></html>
上课铃就是安魂曲 2024-11-23 15:15:29

要实现此行为,您不需要 jQuery 或 jQuery 插件。您可以仅使用 CSS 或 JavaScript(如果您想覆盖所有浏览器)。

但不要使用 onScroll:您只需使用普通 JS 和 路口观察者 API

您所需要做的就是放置元素并监听它们何时在屏幕上可用。 Intersection Observer API 是高度可定制的,可以满足您的所有需求。

总而言之:您可以通过一些 JavaScript 和 JavaScript 来实现这一点。 HTML 行,它比侦听浏览器中的滚动事件的性能要高得多。

For achieving this behaviour you don't need jQuery or a jQuery plugin. You can use only CSS or JavaScript (if you want to cover all browsers).

But don't use onScroll: you can do all of this with just vanilla JS and the Intersection Observer API.

All you need to do is place elements and listen for when they become available in the screen. The Intersection Observer API is very customisable to fit all your needs.

In summary: you accomplish that with a few JavaScript & HTML lines and it's much more performant than listening for scroll events in the browser.

时光磨忆 2024-11-23 15:15:29

优秀的无限滚动演示代码。表明您不需要 jQuery 和 Angular 来进行任何独立于浏览器的工作。但今天的新人已经脱离了我们这些老家伙仍然信任和使用的纯 JavaScript。这里我进一步简化了代码:

// we will add this content, replace for anything you want to add
var wrapper, content, test;
var more = '<div style="height:1000px; background:#EEE;"></div>';

// this is the scroll event handler
function scroller() {
  // print relevant scroll info
  test.innerHTML = wrapper.scrollTop + " + " + wrapper.offsetHeight + " + 100 > " + content.offsetHeight;

  // add more contents if user scrolled down enough
  if (wrapper.scrollTop + wrapper.offsetHeight + 100 > content.offsetHeight) {
    content.innerHTML += more; // NK: Here you can make an Ajax call and fetch content to append to content.innerHTML
  }
}

wrapper = document.getElementById("wrapper");
content = document.getElementById("content");
test = document.getElementById("test");

content.innerHTML = more;

// hook the scroll handler to scroll event
if (wrapper.addEventListener) // NK: Works on all new browsers
  wrapper.addEventListener("scroll", scroller, false);

else if (wrapper.attachEvent) // NK: Works on old IE
  wrapper.attachEvent("onscroll", scroller);
<div id="test">scroll to understand</div>

<div id="wrapper" style="height: 400px; overflow: auto;">
  <div id="content"> </div>
</div>

Excellent demo code for infinite scroll. Goes to show that you don't need jQuery and Angular for any browser independent work. But new boys today are out of touch with pure Javascript that we old guys still trust and use. Here I have simplified the code further:

// we will add this content, replace for anything you want to add
var wrapper, content, test;
var more = '<div style="height:1000px; background:#EEE;"></div>';

// this is the scroll event handler
function scroller() {
  // print relevant scroll info
  test.innerHTML = wrapper.scrollTop + " + " + wrapper.offsetHeight + " + 100 > " + content.offsetHeight;

  // add more contents if user scrolled down enough
  if (wrapper.scrollTop + wrapper.offsetHeight + 100 > content.offsetHeight) {
    content.innerHTML += more; // NK: Here you can make an Ajax call and fetch content to append to content.innerHTML
  }
}

wrapper = document.getElementById("wrapper");
content = document.getElementById("content");
test = document.getElementById("test");

content.innerHTML = more;

// hook the scroll handler to scroll event
if (wrapper.addEventListener) // NK: Works on all new browsers
  wrapper.addEventListener("scroll", scroller, false);

else if (wrapper.attachEvent) // NK: Works on old IE
  wrapper.attachEvent("onscroll", scroller);
<div id="test">scroll to understand</div>

<div id="wrapper" style="height: 400px; overflow: auto;">
  <div id="content"> </div>
</div>

殊姿 2024-11-23 15:15:29
domElem.addEventListener(
        'scroll',
        function(evt) { ... },
        false
    ); 

并适当处理 evt/scroll 位置。

domElem.addEventListener(
        'scroll',
        function(evt) { ... },
        false
    ); 

and handle evt/scroll position appropriately.

篱下浅笙歌 2024-11-23 15:15:29

我看到了您问题的很好答案,但对于不与任何 HTML 元素或内容关联的滚动(只是一个空的 HTML 页面),我是这样做的:

document.querySelector("body").style.height = "1000px";

window.addEventListener("scroll", function() {
    var body = document.querySelector("body");
    var height = body.style.height;
    height = height.slice(0, -2);
    height = Number(height);
    return function() {
        if(height - window.scrollY < 700) {
            height += height / 2;
        }
        body.style.height = height + "px";
    };
}());
<!DOCTYPE html>
<html>
<head>

</head>
<body>

</body>
</html>

我希望这对那里的人有帮助:)

I see great answers to your question, but for a scrolling that is not associated with any HTML element or content (just an empty HTML page), here is how I did it:

document.querySelector("body").style.height = "1000px";

window.addEventListener("scroll", function() {
    var body = document.querySelector("body");
    var height = body.style.height;
    height = height.slice(0, -2);
    height = Number(height);
    return function() {
        if(height - window.scrollY < 700) {
            height += height / 2;
        }
        body.style.height = height + "px";
    };
}());
<!DOCTYPE html>
<html>
<head>

</head>
<body>

</body>
</html>

I hope this helps someone out there :)

才能让你更想念 2024-11-23 15:15:29

实际上@Jan Turon 版本的简化版本对我有用:

<html>
<head>
    <title>Infinite scroll</title>
    <style>
        body {
            font: Arial, san-serif;
            background-color: rgb(130, 75, 8);
            color: black;
        }
    </style>
</head>

<body>
    <div id="test">scroll to understand</div>
    <div id="wrapper" style="height: 400px; overflow: auto;">
        <div id="content"> </div>
    </div>
</body>

<script>
    var more = '<div style="height: 1000px; background: #EEE;">This is content</div>';

    var test = document.getElementById("test");
    var wrapper = document.getElementById("wrapper");
    var content = document.getElementById("content");
    content.innerHTML = more;

    const scrollHandler = () => {
        // test.innerHTML = wrapper.scrollTop + " + " + wrapper.offsetHeight + " + 100 > " + content.offsetHeight;
        if (wrapper.scrollTop + wrapper.offsetHeight + 100 > content.offsetHeight) {
            content.innerHTML += more;
        }
    }

    wrapper.addEventListener("scroll", scrollHandler);
</script>

</html>

Actually a simplified version of @Jan Turon's version worked for me:

<html>
<head>
    <title>Infinite scroll</title>
    <style>
        body {
            font: Arial, san-serif;
            background-color: rgb(130, 75, 8);
            color: black;
        }
    </style>
</head>

<body>
    <div id="test">scroll to understand</div>
    <div id="wrapper" style="height: 400px; overflow: auto;">
        <div id="content"> </div>
    </div>
</body>

<script>
    var more = '<div style="height: 1000px; background: #EEE;">This is content</div>';

    var test = document.getElementById("test");
    var wrapper = document.getElementById("wrapper");
    var content = document.getElementById("content");
    content.innerHTML = more;

    const scrollHandler = () => {
        // test.innerHTML = wrapper.scrollTop + " + " + wrapper.offsetHeight + " + 100 > " + content.offsetHeight;
        if (wrapper.scrollTop + wrapper.offsetHeight + 100 > content.offsetHeight) {
            content.innerHTML += more;
        }
    }

    wrapper.addEventListener("scroll", scrollHandler);
</script>

</html>

夜声 2024-11-23 15:15:29

假设 HTML:

<div class="container"></div>
let container = document.querySelector('.container');

// when user scrolls to last list item in view, wait for 1.5seconds and load next 10 list items, and continue thus.
window.addEventListener('scroll', function(){
  setTimeout(() => {
    loadMoreList(5);
  }, 1500);
});

loadMoreList(20); // load first 20 list items.

function loadMoreList(num) {
  let scrollY = window.scrollY;
  let innerHeight = window.innerHeight;
  let offsetHeight = document.body.offsetHeight;
  
  if (scrollY + innerHeight > offsetHeight - 100) {
    let item = 1;
    let ul = document.createElement('ul');
    
    for (var i = 0; i < num; i++) {
      let li = document.createElement('li');
      li.innerText = 'List Item ' + item++;

      ul.appendChild(li);
      container.appendChild(ul);
    }
  }
}

注意:更重要的部分是:scroll 事件监听器和 loadMoreList 函数。您不一定需要参数 num
for 循环 只是确保在加载时调用该函数并唯一创建并显示 20 个项目。

Assume HTML:

<div class="container"></div>
let container = document.querySelector('.container');

// when user scrolls to last list item in view, wait for 1.5seconds and load next 10 list items, and continue thus.
window.addEventListener('scroll', function(){
  setTimeout(() => {
    loadMoreList(5);
  }, 1500);
});

loadMoreList(20); // load first 20 list items.

function loadMoreList(num) {
  let scrollY = window.scrollY;
  let innerHeight = window.innerHeight;
  let offsetHeight = document.body.offsetHeight;
  
  if (scrollY + innerHeight > offsetHeight - 100) {
    let item = 1;
    let ul = document.createElement('ul');
    
    for (var i = 0; i < num; i++) {
      let li = document.createElement('li');
      li.innerText = 'List Item ' + item++;

      ul.appendChild(li);
      container.appendChild(ul);
    }
  }
}

Note: The more important parts are: the scroll event listener and the loadMoreList function. You don't necessarily need the argument num.
The for loop just ensures that on load, the function is called and 20 items are uniquely created and displayed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文