使用 jQuery 进行网络聊天

发布于 2024-08-11 11:42:41 字数 393 浏览 3 评论 0原文

我正在尝试使用 jQuery 实现一个基于浏览器的聊天系统。我想轮询服务器是否有新消息并将它们附加到 div 的底部。我有两个问题。

  • 我无法让它将文本附加到 div
  • 我不知道如何在附加文本时使 div 滚动到底部

这是我的 HTML 的相关剪辑:

<div id="main">
 <form action='post.php' method='post'>
  <div id='messages'>stuff</div><br />
  <input type='text' name='usertext' />
 </form>
</div>

I am trying to implement a browser based chat system with jQuery. I want to poll the server for new messages and append them to the bottom of a div. I have two problems.

  • I can't get it to append text to the div
  • I don't know how to keep the div scrolled to the bottom as the text gets appended

Here's the relevant clip of my HTML:

<div id="main">
 <form action='post.php' method='post'>
  <div id='messages'>stuff</div><br />
  <input type='text' name='usertext' />
 </form>
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如果没有你 2024-08-18 11:42:41

我不确定你在这里缺少什么。

$(selector).append('<div class="message">sometext</div>');

以及如何滚动到 div 底部

I'm not sure what you're missing here.

$(selector).append('<div class="message">sometext</div>');

And how to scroll to the bottom of a div

同展鸳鸯锦 2024-08-18 11:42:41

使用下面的代码自动滚动到:

var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
//chatbox is the id of div
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight)
{
    $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal');
}

Use below code to scrollto automatically:

var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
//chatbox is the id of div
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight)
{
    $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal');
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文