首页 > 解决方案 > 创建元素后滚动到页面底部

问题描述

我想自动滚动到页面底部,但是当我运行下面的代码时,它并没有完全滚动

function createElement1() {

    var x = document.createElement("IMG");
    x.setAttribute("src", "myImg");
    x.setAttribute("width", "auto");
    x.setAttribute("height", "auto");
    x.setAttribute("alt", "img");
    document.getElementById("id").appendChild(x);

    window.scrollTo(0,document.body.scrollHeight);
}

我也试过

element.scrollTop = element.scrollHeight

我用铬

提前致谢!

标签: javascript

解决方案


根据我的评论:滚动显示不完整的原因是,当您检索主体的滚动高度时,您的图像仍在加载,而当图像加载时,主体的高度已经增加。这会使您的旧值过时,因此您会看到它没有一直滚动到底部。

解决方法是仅在加载图像后执行滚动。这可以通过在以下情况下触发滚动到底部逻辑来完成:

  • 图片触发了load事件,或者
  • 图像的complete属性评估为 true 并且具有非零的自然宽度/高度(主要是针对 IE 的修复,它不会触发load从缓存加载的图像的事件,请参阅此处更好的解释

请参阅下面的概念验证:

function createElement1() {

    var x = document.createElement("IMG");
    
    // Scroll-to-bottom logic
    function scrollToBottom() {
      window.scrollTo(0,document.body.scrollHeight);
    }
    
    // Attach load event listener
    x.addEventListener('load', function() {
      scrollToBottom();
    });
    
    // Fix for IE if loading image from cache
    if (x.complete && x.naturalWidth > 0) {
      scrollToBottom();
    }
    
    x.setAttribute("src", "https://via.placeholder.com/400x400");
    x.setAttribute("width", "auto");
    x.setAttribute("height", "auto");
    x.setAttribute("alt", "img");
    document.getElementById("id").appendChild(x);

    
}

createElement1();
#filler {
  background-color: steelblue;
  height: 50vh;
}
<div id="filler">Just to take up space</div>
<div id="id">Image to be appended below<br /></div>


推荐阅读