不废话直接上代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AI对话</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.title {
text-align: center;
font-size: 24px;
margin-bottom: 20px;
}
.chat-box {
border: 1px solid #ccc;
border-radius: 5px;
height: 400px;
padding: 15px;
overflow-y: auto;
margin-bottom: 20px;
background: #f5f5f5;
}
.message {
margin: 10px 0;
padding: 10px;
border-radius: 10px;
max-width: 70%;
}
.user-message {
background: white;
margin-left: auto;
margin-right: 20px;
}
.error-message {
background: #ff4444;
color: white;
margin-left: 20px;
}
.input-area {
display: flex;
gap: 10px;
}
input[type="text"] {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
</style>
</head>
<body>
<div class="title">与超级智能AI对话</div>
<div class="chat-box" id="chatBox">
<!-- 消息将在这里动态添加 -->
</div>
<div class="input-area">
<input type="text" id="userInput" placeholder="请输入您的问题...">
<button onclick="sendMessage()">发送</button>
</div>
<script>
function sendMessage() {
const input = document.getElementById('userInput');
const chatBox = document.getElementById('chatBox');
if (input.value.trim() === '') return;
// 添加用户消息
const userMessage = document.createElement('div');
userMessage.className = 'message user-message';
userMessage.textContent = input.value;
chatBox.appendChild(userMessage);
// 添加错误消息
setTimeout(() => {
const errorMessage = document.createElement('div');
errorMessage.className = 'message error-message';
errorMessage.textContent = '服务器繁忙,请稍后重试';
chatBox.appendChild(errorMessage);
// 滚动到底部
chatBox.scrollTop = chatBox.scrollHeight;
}, 500);
// 清空输入框
input.value = '';
// 滚动到底部
chatBox.scrollTop = chatBox.scrollHeight;
}
// 添加回车键发送功能
document.getElementById('userInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>