用HTML写一个聊天网页网页最下方是文字输入框和发送按钮最上方显示发送的内容和网页请求后的返回内容
<!DOCTYPE html>
<html>
<head>
<title>Chat Room</title>
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
header {
background-color: lightblue;
padding: 20px;
text-align: center;
font-size: 30px;
font-weight: bold;
}
main {
padding: 20px;
display: flex;
flex-direction: column;
height: calc(100vh - 150px);
overflow-y: auto;
}
.message {
margin-bottom: 10px;
padding: 10px;
border-radius: 10px;
max-width: 80%;
align-self: flex-start;
background-color: #EEE;
}
.message.sent {
align-self: flex-end;
background-color: lightblue;
color: white;
}
footer {
background-color: lightblue;
padding: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
footer input[type="text"] {
flex-grow: 1;
margin-right: 10px;
padding: 10px;
border-radius: 5px;
border: none;
font-size: 16px;
}
footer button {
padding: 10px 20px;
border-radius: 5px;
border: none;
background-color: #FFF;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<header>Chat Room</header>
<main id="messages">
<!-- Messages will be added here dynamically -->
</main>
<footer>
<input type="text" id="message-input" placeholder="Type your message...">
<button id="send-button">Send</button>
</footer>
<script>
const messagesContainer = document.getElementById('messages');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
<pre><code> // Send message when Send button is clicked or Enter is pressed
sendButton.addEventListener('click', sendMessage);
messageInput.addEventListener('keydown', (event) => {
if (event.keyCode === 13) {
sendMessage();
}
});
function sendMessage() {
const messageText = messageInput.value;
if (messageText.trim() !== '') {
const message = document.createElement('div');
message.classList.add('message', 'sent');
message.innerText = messageText;
messagesContainer.appendChild(message);
messageInput.value = '';
// Send message to server and handle response
fetch('https://api.example.com/chat', {
method: 'POST',
body: JSON.stringify({message: messageText}),
headers: {'Content-Type': 'application/json'}
})
.then(response => response.json())
.then(data => {
const message = document.createElement('div');
message.classList.add('message');
message.innerText = data.message;
messagesContainer.appendChild(message);
})
.catch(error => {
const message = document.createElement('div');
message.classList.add('message');
message.innerText = 'Error: ' + error.message;
messagesContainer.appendChild(message);
});
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/XgN 著作权归作者所有。请勿转载和采集!