HTML:
DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
head>
<body>
<div class="chat-container">
<div class="chat-messages" id="chat-messages">div>
<div class="chat-input">
<input type="text" id="message-input" placeholder="输入消息...">
<button id="send-button">发送button>
div>
div>
<script src="script.js">script>
body>
html>
CSS(style.css):
body {
font-family: Arial, sans-serif;
}
.chat-container {
width: 300px;
margin: 0 auto;
border: 1px solid #ccc;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
padding: 20px;
border-radius: 10px;
}
.chat-messages {
height: 300px;
overflow-y: scroll;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
.chat-input {
display: flex;
justify-content: space-between;
}
input[type="text"] {
flex: 1;
padding: 5px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 5px 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
JavaScript(script.js):
document.addEventListener("DOMContentLoaded", function() {
const messageInput = document.getElementById("message-input");
const sendButton = document.getElementById("send-button");
const chatMessages = document.getElementById("chat-messages");
sendButton.addEventListener("click", function() {
const messageText = messageInput.value;
if (messageText.trim() !== "") {
const messageDiv = document.createElement("div");
messageDiv.classList.add("message");
messageDiv.textContent = messageText;
chatMessages.appendChild(messageDiv);
messageInput.value = "";
// 模拟回复消息
setTimeout(function() {
const replyDiv = document.createElement("div");
replyDiv.classList.add("message", "reply");
replyDiv.textContent = "这是一个自动回复。";
chatMessages.appendChild(replyDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}, 1000);
}
});
// 模拟初始消息
const initialMessage = document.createElement("div");
initialMessage.classList.add("message", "reply");
initialMessage.textContent = "欢迎使用聊天窗口!";
chatMessages.appendChild(initialMessage);
});