【问题标题】:Native Javascript scroll to bottom with smooth animation on div with dynamic added content原生 Javascript 滚动到底部,在 div 上带有动态添加内容的平滑动画
【发布时间】:2019-12-18 19:59:42
【问题描述】:

我正在制作一个聊天应用程序,我想要归档的是当加载动态消息时,页面会以流畅的动画向下滚动到 div 的底部。

<ul id="messages">
                <li>
                    <p>Not logged in on Epic | Log in here: https://epic.clow.nl/login</p>
                </li>
            </ul>

【问题讨论】:

标签: javascript html animation scroll native


【解决方案1】:

平滑滚动不需要jQuery。试试这个 -

window.scroll({
  top: 1000,
  behavior: 'smooth'
});

这会将网页向下跳转 1000 像素。

【讨论】:

    【解决方案2】:

    您可以使用 jquery 轻松实现这一点。只需将此添加到您的&lt;head&gt;

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    

    然后将其添加到您的 javascript 文件中:

    function messagesAreLoaded() {
        $("div").animate({ scrollTop: $(document).height() }, "slow");
    }
    

    该函数需要在消息加载时调用。然后&lt;div&gt; 元素滚动到底部。只需将 &lt;div&gt; 元素设置为需要滚动的任何元素即可。

    希望这会有所帮助!

    【讨论】:

    • 我不允许只使用jquery原生javascript
    • 哦,我的坏嗯。我有一个新计划
    【解决方案3】:

    好的,现在使用本机 javascript 进行第二次尝试。

    有这个功能。

    window.scrollBy(0, 50);
    

    每次执行时都会将窗口向下滚动 50,因此您可以像循环一样制作。

        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
            // you're at the bottom of the page
        }
    

    然后做一些类似的事情

    function smoothToBottom() {
        // change the time to make the ani go faster or slower
        var scrollTimer = setInterval(scrollDown, 200);
        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
            // you're at the bottom of the page
            clearInterval(scrollTimer);
        }
    }
    
    function scrollDown() {
       window.scrollBy(0, 10);
    }
    

    我还没有测试过,但它可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多