修复聊天框弹出bug
This commit is contained in:
parent
df0830a2ad
commit
a3dc204b21
@ -13,6 +13,7 @@
|
||||
|
||||
.chat-box {
|
||||
width: 90%;
|
||||
min-height: 20px;
|
||||
max-height: 50vh;
|
||||
overflow-y: auto;
|
||||
background: #f5f5f5;
|
||||
@ -21,6 +22,7 @@
|
||||
border-radius: 8px;
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.chat-box.show {
|
||||
|
@ -53,7 +53,9 @@
|
||||
<div id="chatContainer" class="chat-box hide"></div>
|
||||
|
||||
<div class="input-row">
|
||||
<input type="text" id="userInput" placeholder="输入你的消息..." onfocus="toggleChat(true)">
|
||||
<!-- 改用 onclick,顺带阻止冒泡 -->
|
||||
<input type="text" id="userInput" placeholder="输入你的消息..."
|
||||
onclick="openChat(event)" />
|
||||
<button onclick="sendMessage()">发送</button>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -6,24 +6,38 @@ document.getElementById('userInput').addEventListener('keydown', function(event)
|
||||
});
|
||||
|
||||
// 控制聊天框显示和隐藏
|
||||
function toggleChat(show) {
|
||||
const chatBox = document.getElementById('chatContainer');
|
||||
const inputBox = document.getElementById('userInput');
|
||||
|
||||
// 点击输入框时打开聊天框
|
||||
function openChat(e) {
|
||||
e.stopPropagation(); // 阻止这次点击冒泡到 document
|
||||
toggleChat(true);
|
||||
}
|
||||
|
||||
function toggleChat(show) {
|
||||
if (show) {
|
||||
// 如果已经显示就不重复处理
|
||||
if (chatBox.classList.contains('show')) return;
|
||||
|
||||
chatBox.style.display = 'block'; // 确保先显示再动画
|
||||
// 先显示动画前状态
|
||||
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);
|
||||
@ -34,9 +48,7 @@ function toggleChat(show) {
|
||||
}
|
||||
|
||||
function outsideClickListener(event) {
|
||||
const chatBox = document.getElementById('chatContainer');
|
||||
const inputBox = document.getElementById('userInput');
|
||||
|
||||
// 点击目标既不在聊天框也不在输入框里,就收起
|
||||
if (!chatBox.contains(event.target) && !inputBox.contains(event.target)) {
|
||||
toggleChat(false);
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user