Код: Выделить всё
const msgs = document.getElementById('msgs');
const inputEl = document.getElementById('input');
const sendBtn = document.getElementById('send');
function addMessage(text, cls) {
const m = document.createElement('div');
m.className = `message ${cls}`;
m.textContent = text;
// I append chronologically:
msgs.appendChild(m);
// then try to scroll the new message into view at the top:
m.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
sendBtn.addEventListener('click', () => {
const txt = inputEl.textContent.trim();
if (!txt) return;
addMessage(txt, 'user');
inputEl.textContent = '';
setTimeout(() => addMessage('Echo: ' + txt, 'bot'), 200);
});< /code>
.chat-container {
display: flex;
flex-direction: column;
height: 100vh;
}
.chat-header {
padding: 1rem;
background: #444;
color: white;
}
.chat-messages {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
border: 1px solid #ccc;
padding: 1rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.message {
max-width: 70%;
padding: 0.5rem;
border-radius: 1rem;
}
.user {
background: #007aff;
color: white;
align-self: flex-end;
}
.bot {
background: #ddd;
color: #333;
align-self: flex-start;
}
.composer {
padding: 0.5rem;
border-top: 1px solid #ccc;
}
.input {
width: 80%;
padding: 0.5rem;
}
.send-btn {
padding: 0.5rem 1rem;
}< /code>
Chat Demo
Welcome!
Send
Подробнее здесь: https://stackoverflow.com/questions/796 ... -container