写一个基于jQuery可以相互聊天的h5 聊天界面实例
时间: 2024-02-28 07:52:25 浏览: 150
好的,这里提供一个基于jQuery的H5聊天界面实例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Chat Room</title>
<style>
#chat-container {
display: flex;
flex-direction: column;
height: 100%;
border: 1px solid #ccc;
border-radius: 5px;
overflow: hidden;
}
#chat-header {
padding: 10px;
background-color: #f6f6f6;
border-bottom: 1px solid #ccc;
text-align: center;
}
#chat-messages {
flex: 1;
overflow-y: scroll;
padding: 10px;
}
#chat-messages ul {
list-style: none;
margin: 0;
padding: 0;
}
#chat-messages li {
margin: 10px 0;
}
#chat-messages li.received {
text-align: left;
}
#chat-messages li .message-content {
display: inline-block;
padding: 5px 10px;
background-color: #f6f6f6;
border-radius: 5px;
}
#chat-input {
display: flex;
align-items: center;
padding: 10px;
background-color: #f6f6f6;
}
#chat-input input[type="text"] {
flex: 1;
padding: 5px;
border-radius: 5px;
border: none;
}
#chat-input button {
margin-left: 10px;
padding: 5px 10px;
border-radius: 5px;
border: none;
background-color: #007bff;
color: #fff;
cursor: pointer;
}
#chat-input button:hover {
background-color: #0069d9;
}
</style>
</head>
<body>
<div id="chat-container">
<div id="chat-header">
<h2 id="contact-name">John Doe</h2>
</div>
<div id="chat-messages">
<ul id="message-list"></ul>
</div>
<div id="chat-input">
<input type="text" id="message-input" placeholder="Type your message here...">
<button id="send-button">Send</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var messages = [
{
id: 1,
content: 'Hi there!',
isReceived: true
},
{
id: 2,
content: 'How are you?',
isReceived: false
}
];
// Render messages
function renderMessages() {
var messageList = $('#message-list');
messageList.empty();
messages.forEach(function(message) {
var messageClass = message.isReceived ? 'received' : '';
var messageHtml = '<li class="' + messageClass + '"><div class="message-content">' + message.content + '</div></li>';
messageList.append(messageHtml);
});
messageList.scrollTop(messageList[0].scrollHeight);
}
// Send message
function sendMessage() {
var messageInput = $('#message-input');
var messageContent = messageInput.val().trim();
if (messageContent !== '') {
messages.push({
id: messages.length + 1,
content: messageContent,
isReceived: false
});
messageInput.val('');
renderMessages();
}
}
// Bind events
$('#send-button').click(sendMessage);
$('#message-input').keyup(function(event) {
if (event.keyCode === 13) {
sendMessage();
}
});
// Initial render
renderMessages();
});
</script>
</body>
</html>
```
这个界面与Vue.js版本的类似,包含了一个聊天头部、聊天消息列表和一个输入框(包含发送按钮)。您可以根据您的实际需求进行修改和扩展。
阅读全文