自适应聊天网页 - HTML 实现实时聊天功能
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>聊天室</title>
<style>
body{
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.container{
display: flex;
flex-direction: column;
height: 100vh;
}
.header{
background-color: #eee;
padding: 10px;
font-size: 18px;
font-weight: bold;
text-align: left;
}
.message-box{
flex: 1;
overflow-y: scroll;
padding: 10px;
background-color: #fff;
border: 1px solid #ccc;
}
.message{
margin-bottom: 10px;
padding: 5px;
background-color: #f2f2f2;
border-radius: 5px;
max-width: 80%;
word-break: break-all;
}
.message.from-me{
background-color: #d9edf7;
}
.message.from-server{
background-color: #dff0d8;
}
.input-box{
display: flex;
background-color: #eee;
padding: 10px;
align-items: center;
justify-content: space-between;
border-top: 1px solid #ccc;
}
.input-box input{
flex: 1;
margin-right: 10px;
height: 30px;
font-size: 16px;
padding: 5px;
border: none;
border-radius: 5px;
}
.input-box button{
height: 30px;
font-size: 16px;
padding: 5px 10px;
border: none;
border-radius: 5px;
background-color: #337ab7;
color: #fff;
cursor: pointer;
}
</style>
</head>
<body>
<div class='container'>
<div class='header'>聊天室</div>
<div class='message-box' id='message-box'></div>
<div class='input-box'>
<input type='text' id='input-box' placeholder='请输入消息...' >
<button id='send-btn'>发送</button>
</div>
</div>
<script>
var messageBox = document.getElementById('message-box');
var inputBox = document.getElementById('input-box');
var sendBtn = document.getElementById('send-btn');
<pre><code> function sendMessage() {
var message = inputBox.value;
if (message.trim() !== '') {
var el = document.createElement('div');
el.className = 'message from-me';
el.innerText = message;
messageBox.appendChild(el);
inputBox.value = '';
messageBox.scrollTop = messageBox.scrollHeight;
// 发送请求并接收返回内容
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/chat?message=' + message, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = xhr.responseText;
var el = document.createElement('div');
el.className = 'message from-server';
el.innerText = response;
messageBox.appendChild(el);
messageBox.scrollTop = messageBox.scrollHeight;
}
};
xhr.send();
}
}
sendBtn.addEventListener('click', sendMessage);
inputBox.addEventListener('keydown', function(event){
if (event.keyCode === 13) {
sendMessage();
}
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/mhnK 著作权归作者所有。请勿转载和采集!