添加聊天室
This commit is contained in:
75
src/chat.js
Normal file
75
src/chat.js
Normal file
@@ -0,0 +1,75 @@
|
||||
import { Span, Button, List, ListItem } from './weigets.js'
|
||||
|
||||
// 先不划分频道, 只有一个公共聊天室
|
||||
export default class Chat {
|
||||
constructor({ EventListeners = {}, onsend, onexit }) {
|
||||
this.event = { onsend, onexit }
|
||||
this.ul = List({ classList: ['chat-list'] })
|
||||
this.EventListeners = EventListeners
|
||||
document.body.appendChild(this.ul) // 元素加入页面
|
||||
|
||||
// 添加输入框
|
||||
const input = document.createElement('input')
|
||||
input.type = 'text'
|
||||
input.placeholder = '输入聊天内容'
|
||||
input.style.width = '100%'
|
||||
input.style.height = '5rem'
|
||||
input.style.margin = '1rem 2rem'
|
||||
input.addEventListener('keydown', event => {
|
||||
if (event.key === 'Enter') {
|
||||
const text = input.value.trim()
|
||||
if (text) {
|
||||
this.send(text)
|
||||
input.value = ''
|
||||
}
|
||||
}
|
||||
})
|
||||
document.body.appendChild(input)
|
||||
|
||||
// 写入 css 样式到 head
|
||||
const style = document.createElement('style')
|
||||
style.innerText = `
|
||||
ul.chat-list {
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
ul.chat-list > li > span {
|
||||
cursor: pointer;
|
||||
}
|
||||
ul.chat-list > li.play > span {
|
||||
color: #02be08;
|
||||
}
|
||||
ul.chat-list > li.cache::marker {
|
||||
color: #02be08;
|
||||
font-size: 1em;
|
||||
contentx: '⚡';
|
||||
}
|
||||
ul.chat-list > li.disable {
|
||||
color: #888;
|
||||
}
|
||||
`
|
||||
document.head.appendChild(style)
|
||||
}
|
||||
// 添加一条消息
|
||||
add({ name, text, time, type }) {
|
||||
this.ul.appendChild(ListItem({
|
||||
classList: [type],
|
||||
children: [
|
||||
Span({ innerText: `${name} ${time} ${text}` })
|
||||
]
|
||||
}))
|
||||
this.ul.scrollTop = this.ul.scrollHeight
|
||||
}
|
||||
// 发送消息
|
||||
send(text) {
|
||||
if (this.event.onsend) {
|
||||
this.event.onsend(text)
|
||||
}
|
||||
}
|
||||
// 退出
|
||||
exit() {
|
||||
if (this.event.onexit) {
|
||||
this.event.onexit()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user