在JavaScript中实现类似微信气泡的效果,通常涉及到HTML、CSS和JavaScript的综合运用。以下是一些基础概念和相关信息:
<div id="chat-container">
<div class="message received">
<span class="message-content">Hello!</span>
</div>
<div class="message sent">
<span class="message-content">Hi there!</span>
</div>
</div>
#chat-container {
width: 300px;
height: 400px;
border: 1px solid #ccc;
padding: 10px;
overflow-y: scroll;
}
.message {
max-width: 70%;
margin: 5px;
padding: 10px;
border-radius: 15px;
position: relative;
}
.received {
background-color: #e1ffc7;
align-self: flex-start;
}
.sent {
background-color: #c7e1ff;
align-self: flex-end;
}
.message::after {
content: '';
position: absolute;
bottom: 0;
width: 0;
height: 0;
}
.received::after {
left: -10px;
border: 10px solid transparent;
border-right-color: #e1ffc7;
border-left: 0;
margin-bottom: -10px;
}
.sent::after {
right: -10px;
border: 10px solid transparent;
border-left-color: #c7e1ff;
border-right: 0;
margin-bottom: -10px;
}
function addMessage(content, isSent) {
const chatContainer = document.getElementById('chat-container');
const messageDiv = document.createElement('div');
messageDiv.classList.add('message');
if (isSent) {
messageDiv.classList.add('sent');
} else {
messageDiv.classList.add('received');
}
const messageContent = document.createElement('span');
messageContent.classList.add('message-content');
messageContent.textContent = content;
messageDiv.appendChild(messageContent);
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
// 示例调用
addMessage('Hello!', false);
addMessage('Hi there!', true);
align-self
属性和::after
伪元素的定位。max-width
和padding
一致。scrollTop
为scrollHeight
。通过以上代码和说明,你可以实现一个基本的微信气泡效果,并根据需要进行调整和扩展。
微搭低代码直播互动专栏
云+社区技术沙龙[第8期]
腾讯云证券及基金行业数字化实践系列直播
云+社区技术沙龙[第5期]
T-Day
云+社区沙龙online [技术应变力]
腾讯数字政务云端系列直播
Techo Youth
领取专属 10元无门槛券
手把手带您无忧上云