2025-04-05 22:17:52 +08:00
|
|
|
// 监听回车键事件
|
|
|
|
document.getElementById('userInput').addEventListener('keydown', function(event) {
|
|
|
|
if (event.key === 'Enter') {
|
|
|
|
sendMessage();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// 控制聊天框显示和隐藏
|
2025-04-06 22:15:36 +08:00
|
|
|
const chatBox = document.getElementById('chatContainer');
|
|
|
|
const inputBox = document.getElementById('userInput');
|
2025-04-05 22:17:52 +08:00
|
|
|
|
2025-04-06 22:15:36 +08:00
|
|
|
// 点击输入框时打开聊天框
|
|
|
|
function openChat(e) {
|
|
|
|
e.stopPropagation(); // 阻止这次点击冒泡到 document
|
|
|
|
toggleChat(true);
|
|
|
|
}
|
2025-04-05 22:17:52 +08:00
|
|
|
|
2025-04-06 22:15:36 +08:00
|
|
|
function toggleChat(show) {
|
|
|
|
if (show) {
|
|
|
|
if (chatBox.classList.contains('show')) return;
|
|
|
|
|
|
|
|
// 先显示动画前状态
|
|
|
|
chatBox.style.display = 'block';
|
|
|
|
chatBox.classList.remove('hide');
|
|
|
|
chatBox.classList.add('show');
|
|
|
|
|
|
|
|
// 延迟到下一轮事件循环再加 document 监听,避免捕获当前点击
|
|
|
|
setTimeout(() => {
|
|
|
|
document.addEventListener('click', outsideClickListener);
|
|
|
|
}, 0);
|
|
|
|
|
|
|
|
// 聊天框内部点击也不要冒泡
|
|
|
|
chatBox.addEventListener('click', e => e.stopPropagation());
|
|
|
|
} else {
|
|
|
|
if (!chatBox.classList.contains('show')) return;
|
|
|
|
|
|
|
|
chatBox.classList.remove('show');
|
|
|
|
chatBox.classList.add('hide');
|
|
|
|
|
|
|
|
// 动画结束后真正隐藏
|
|
|
|
chatBox.addEventListener('animationend', function handler() {
|
|
|
|
chatBox.style.display = 'none';
|
|
|
|
chatBox.removeEventListener('animationend', handler);
|
|
|
|
});
|
|
|
|
|
|
|
|
document.removeEventListener('click', outsideClickListener);
|
|
|
|
}
|
2025-04-05 22:17:52 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
function outsideClickListener(event) {
|
2025-04-06 22:15:36 +08:00
|
|
|
// 点击目标既不在聊天框也不在输入框里,就收起
|
|
|
|
if (!chatBox.contains(event.target) && !inputBox.contains(event.target)) {
|
|
|
|
toggleChat(false);
|
|
|
|
}
|
2025-04-05 22:17:52 +08:00
|
|
|
}
|