javascript - 创建元素后滚动到页面底部
问题描述
我想自动滚动到页面底部,但是当我运行下面的代码时,它并没有完全滚动
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
我用铬
提前致谢!
解决方案
根据我的评论:滚动显示不完整的原因是,当您检索主体的滚动高度时,您的图像仍在加载,而当图像加载时,主体的高度已经增加。这会使您的旧值过时,因此您会看到它没有一直滚动到底部。
解决方法是仅在加载图像后执行滚动。这可以通过在以下情况下触发滚动到底部逻辑来完成:
- 图片触发了
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>
推荐阅读
- apache-nifi - 如何使用 Onedrive API 通过 NIFI 从 Onedrive 下载公共共享文件
- mysql - 子字符串查询返回 null
- javascript - 如何在将参数传递给组件之前从 AsyncStorage 获取参数?
- reactjs - 使用 React 将本地图像分享到 Facebook?
- javascript - 选择另一个选项时如何更改 DDL 的“已选择”属性并使用 jQuery 删除默认预选值
- javascript - 如何将现有的 HTML 和 JS 功能导入 ReactJS
- mysql - Confluent Kafka Connect MySQL Sink Connector 的开源替代方案?
- windows - 除非已为构建用户打开交互式登录,否则 Jenkins windows slave 上的 cmake 将失败
- javascript - JavaScript Chrome 控制台 - 即使 Chrome 传感器位置初始化为马里兰州巴尔的摩 (UTC-5),日期偏移命令也会返回 UTC-8
- c# - HTTP 错误 413.1 - 请求实体太大抛出错误而不是增加大小