我想自动滚动到页面底部,但当我运行下面的代码时,它不会完全滚动
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
我使用 Chrome
提前致谢!
最佳答案
根据我的评论:滚动显示不完整的原因是因为当您检索正文的滚动高度时,您的图像仍在加载,并且当图像加载时,正文的高度已经增加。这使得您的旧值变得陈旧,因此您会看到它没有一直滚动到底部。
解决方法是仅在加载图像后执行滚动。这可以通过在以下情况下触发滚动到底部逻辑来完成:
- 图像已触发
load
事件,或者 - 图像的
complete
属性计算结果为 true,并且具有非零的自然宽度/高度(主要是针对 IE 的修复,它不会为加载的图像触发load
事件来自缓存,see better explanation here)
请参阅下面的概念验证:
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>
关于javascript - 创建元素后滚动到页面底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173490/