【问题标题】:Scrolling with jQuery Without using animate()使用 jQuery 滚动而不使用 animate()
【发布时间】:2019-02-24 16:44:31
【问题描述】:

我正在构建一个信使网站,并希望在刷新页面时聊天自动滚动到聊天提要的底部(最新消息)。我对 jQuery 很陌生,经过一番搜索后,我已经使用 animate() 让它工作了。例如,当页面在表单提交后重新加载时首次加载太不和谐时,这非常有用。

有没有什么方法可以自动滚动到容器的底部而不给它设置动画?

// When page loads
$(document).ready(function(){
    // Load chat. ALSO the chat has to be hard coded in here.
    $('#MessagesContainer').load('/php/chat_ref.php');

    // Scroll to the bottom of the page. ALSO ".height()+500" was a bit of a bodge.
    $("#MessagesContainer").animate({ scrollTop:$('#MessagesContainer').height()+500}, 100);
    return false;
});

// Every 2 seconds.
var auto_refresh = setInterval(function(){
    // Reload the chat.
    $('#MessagesContainer').load('/php/chat_ref.php'); 
    return false;
}, 2000);

【问题讨论】:

  • 是的,只需手动设置scrollTop()$("#MessagesContainer").scrollTop($('#MessagesContainer').height()+500);。但是您应该注意,AJAX 轮询是一个非常糟糕的主意,因为它根本不能很好地扩展。要构建聊天系统,您应该使用 Websockets 或服务器发送的事件。

标签: javascript jquery html scrolltop


【解决方案1】:

用 scrollTop 代替 animate 怎么样?

$("#MessagesContainer").scrollTop($("#MessagesContainer").height());

【讨论】:

  • 怎么样:$("#MessagesContainer").scrollTop($("#MessagesContainer")[0].scrollHeight); 如果不能,您能否在jsfiddle.net 上发布代码 sn-p 或其他内容并模拟消息加载?这样会更容易提供帮助。
猜你喜欢
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多