我正在聊天,在加载时,滚动条滚动到底部。这是在加载时调用的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/ 请告诉我,谢谢!
答案 0 :(得分:1)
一些想法,首先你可能想要使用递归来调用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端点
希望有所帮助!