【发布时间】:2023-01-09 23:40:38
【问题描述】:
我希望我的网站跟随来自外部来源的内容,这些内容会随着时间的推移而加载
我试过使用
chatContainer.scrollTop = chatContainer.scrollHeight;
因为我的 chatContainer 是加载内容的地方,但它不能正常工作,你能给我一些帮助吗?如何使网站跟随视图实时渲染内容?
【问题讨论】:
-
我不明白你在问什么
标签: javascript element scrolltop
我希望我的网站跟随来自外部来源的内容,这些内容会随着时间的推移而加载
我试过使用
chatContainer.scrollTop = chatContainer.scrollHeight;
因为我的 chatContainer 是加载内容的地方,但它不能正常工作,你能给我一些帮助吗?如何使网站跟随视图实时渲染内容?
【问题讨论】:
标签: javascript element scrolltop
要滚动元素内容以显示最近添加的内容(到底部):
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Element 接口的 scrollIntoView() 方法滚动元素的 祖先容器使得 scrollIntoView() 所在的元素 called 对用户可见。
另外,每次元素更改时都应该这样做。为此,您可以使用 MutationObserver:
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
MutationObserver 接口提供了监视的能力 对 DOM 树所做的更改。它被设计为替代品 对于旧的 Mutation Events 功能,它是 DOM3 的一部分 事件规范。
在这个演示中,我们有一个
#chat-container元素,它将被setInterval更改,每 1 秒向父元素附加一个包含内容的新元素。MutationObserver 将在每次更改时触发,并将调用该元素上的
scrollIntoView将内容滚动到底部。const chatContainer = document.getElementById('chat-container'); const timer = setInterval(()=>{ const newContent = document.getElementById('lorem').content.cloneNode(true); chatContainer.append(newContent); }, 1000); const observer = new MutationObserver(() => { chatContainer.scrollIntoView(false); console.log(`observing element as changed!`); }); observer.observe(chatContainer, {subtree: true, childList: true});body{ position: relative; } #stop{ position: absolute; top: 1rem; font-size: 5rem; margin-left: auto; margin-right: auto; left: 0; right: 0; padding: 0 1em; cursor: pointer; } #chat-container > *{ margin-bottom: 1rem; }<div id="chat-container"> </div> <button id="stop" onclick="clearInterval(timer);">STOP</button> <template id="lorem"> <div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div> </template>
【讨论】: