2 回答
TA贡献1816条经验 获得超4个赞
获取一些文字
将其填充到元素中
将元素滚动到底部
// don't need this. It's to get the posts from the fake API
let id = 0;
// get a reference to the logs element
const logs = document.getElementById("logs");
// this takes some text, wraps in in a <pre> tag and returns the element
function makeLogEntry(str) {
const el = document.createElement("pre");
el.innerText = str;
return el;
}
// This is just to tick up the post id and roll it back to 1 if we go over 100, since the fake api only has 100 posts
function getId() {
return ++id > 100 ? 1 : id;
}
function getPost(id) {
fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then(response => response.json())
.then(json => {
// wrap the log message in a tag and append it to the logs
logs.append(makeLogEntry(json.title));
// scroll the logs element to the bottom
// see (https://stackoverflow.com/questions/270612/scroll-to-bottom-of-div)
logs.scrollTop = logs.scrollHeight;
})
}
// fetch stuff every 2 seconds
setInterval(() => getPost(getId()), 2000);
#logs {
width: 100%;
height: 100px;
border: 1px solid #ddd;
overflow: scroll;
}
<div id="logs"></div>
TA贡献1829条经验 获得超6个赞
fetch
您必须使用 javascript ,
您的服务器应该提供数据。然后你使用 JS DOM 将数据放入你想要放置的容器中。然后,要启用滚动,您必须编写一个包含区域大小和规则的 css overflow-y:scroll
文件。
添加回答
举报