作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在聊天,加载时滚动条滚动到底部。这是加载时调用的 JS 函数:
<script>
function updateScroll() {
var element = document.getElementById("chatlogs");
var elementHeight = element.scrollHeight;
element.scrollTop = elementHeight
}
window.onload = updateScroll;
</script>
然后,使用以下代码:
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlogs').load('logs.php');}, 1000);
});
..聊天内容每秒都会更新。但发生的情况是,当它更新时,滚动条会转到中间,而不是留在底部。当最后一个代码使聊天刷新时,如何使我的聊天保持在底部?
您可以在此处查看一个工作示例:http://www.friendsinclass.co.nf/请告知,谢谢!
最佳答案
有几个想法,首先您可能希望使用递归在 AJAX 成功时调用 AJAX 请求。使用 setInterval()
可能会导致在任何给定时间发生任意数量的 AJAX 请求,具体取决于它们返回所需的时间。
其次,为了防止用户滚动时滚动条跳转到底部,您可能需要向他们发出通知,并能够在有新内容时跳转到底部。
考虑到这些点,这样的事情会起作用:
JavaScript
var infiniteUpdate = true;
var intervalTimer;
var id = 0;
var log = document.getElementById("chatlogs");
function updateScroll() {
log.scrollTop = log.scrollHeight;
$('#messagearea').hide()
}
function updateLog() {
//if an interval timer was set, we clear it
if(typeof intervalTimer == 'number') {
clearInterval(intervalTimer);
}
id++;
$.ajax({
url: "http://jsonplaceholder.typicode.com/photos?id=" + id,
})
.done(function( data ) {
//bottomOfScroll is the height .scrollTop must be at for the user to be at the bottom of the scrollbar
var bottomOfScroll = log.scrollHeight - log.clientHeight;
//isScrollable detects if the element can scroll
var isScrollable = log.scrollHeight != log.clientHeight;
//if the user is not at the bottom and the element has a scrollbar
if(log.scrollTop != bottomOfScroll && isScrollable) {
//when true, it means the user has scrolled
hasUserScrolled = true;
} else {
//when false, we are still at the bottom of the element
hasUserScrolled = false;
}
//append the new data
$('#chatlogs').append('<p>'+data[0].title+'</p>')
//if we had detected a scroll
if(hasUserScrolled) {
//show the message and allow the user to click to jump to the bottom
$('#messagearea').show();
} else {
//if the user hasnt scrolled, move the scroll position to the bottom and hide the message
updateScroll();
}
//if we wanted to do something to break recursion, we could do that here
if(infiniteUpdate) {
//set a new timer for 2.5 seconds
intervalTimer = setInterval( updateLog, 2500);
}
});
}
$(document).ready(function() {
$('#messagearea').on('click', updateScroll)
updateScroll();
updateLog();
});
HTML
<div id="chatlogs">
</div>
<div id="messagearea">Scroll Down to View New Messages
</div>
CSS
#chatlogs {
height: 300px;
width: 200px;
overflow: scroll;
}
#messagearea { display: none; }
JS fiddle 示例 https://jsfiddle.net/igor_9000/9tbrgrkn/3/使用测试 AJAX 端点
希望有帮助!
关于javascript - 如何在聊天刷新时将滚动条保持在底部,而不是转到中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36271704/
我是一名优秀的程序员,十分优秀!