作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我试图滚动到 div #chat-feed
的底部,溢出设置为 auto 并停留在那里,除非用户向上滚动该 div 的内容。如果他们向下滚动,div 应该锁定到底部,新内容将显示在底部。
已知问题:我已尝试实现 this answer使用我的代码,但我对 Javascript 的了解还不够深,无法使其正常工作。如果 chat-feed.php
中的内容比容器高,则滚动条会停留在顶部。给出的答案似乎也不尊重从外部文件加载的内容。
关键点:新内容应该显示在底部,当新内容加载时 div 应该滚动到底部,除非用户已经向上滚动了一点。如果用户向下滚动,那么它应该锁定到底部并且新内容显示在底部并且可见。
<div id="chat-feed" style="height: 200px; width: 300px; overflow: auto;"></div>
<script>
$(document).ready(function(){
setInterval(function(){
$('#chat-feed').load("chat-feed.php").fadeIn("slow");
}, 1000);
});
</script>
最佳答案
关于您链接到的问题,有一个更好的实现 https://stackoverflow.com/a/21067431/1544886 .
我在下面修改了该作者的代码:
$(document).ready(function() {
var out = document.getElementById("chat-feed"); // outer container of messages
var c = 0; // used only to make the fake messages different
// generate some chatter every second
setInterval(function() {
//check current scroll position BEFORE message is appended to the container
var isScrolledToBottom = checkIfScrolledBottom();
// append new mesage here
$('#chat-feed').append("<div>Some new chat..." + c++ + "</div>").fadeIn("slow");
// scroll to bottom if scroll position had been at bottom prior
scrollToBottom(isScrolledToBottom);
}, 1000);
function checkIfScrolledBottom() {
// allow for 1px inaccuracy by adding 1
return out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
}
function scrollToBottom(scrollDown) {
if (scrollDown)
out.scrollTop = out.scrollHeight - out.clientHeight;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat-feed" style="height: 150px; width: 300px; overflow: auto;"></div>
更新
JQuery 的 .load()
函数删除关联元素(chat-feed
)并重新添加。这意味着 out
变量指向旧的已删除元素,而不是新元素。解决方案是在执行 .load()
后更新 out
变量:
$('#chat-feed').load("chat-feed.php").fadeIn("slow");
out = document.getElementById("chat-feed"); // outer container of messages
关于javascript - JQuery - 除非用户向上滚动,否则滚动并锚定到 ajax 驱动的 div 的底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42603134/
我是一名优秀的程序员,十分优秀!