css 实现聊天框样式

需求如题

html-以vue为例

      <div v-if="textList.length" class="dialog-text-box">
        <div v-for="(item,index) in textList" :key="index" class="text-item" :class="item.position === 'right' ? 'text-item-right' : ''">
          <template v-if="item.position === 'left'">
            <div class="chat-name">{
   
   { item.name }}</div><div class="chat-box">{
   
   { item.content }}</div>
          </template>
          <template v-else>
            <div class="chat-box">{
   
   { item.content }}</div> <div class="chat-name">{
   
   { item.name }}</div>
          </template>
        </div>
      </div>

css

.dialog-text-box {
  height: 500px;
  overflow: auto;
  background-color: #F2F2F2;
}
  .dialog-text-box::-webkit-scrollbar {
    display: none;
  }
.text-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  &:last-child {
    margin-bottom: 0;
  }
}
.chat-name {
  width: 42px;
  height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  border-radius: 50%;
  background-color: #3C8AFF;
  color: #Ffffff;
}
.chat-box {
  margin-left: 12px;
  padding: 8px;
  max-width: calc(100% - 55px);
  background: #FFFFFF;
  position: relative;
  border-radius:4px;
}
.chat-box:before {
  content:"";
  position: absolute;
  right: 100%;
  top: 50%;
  width: 0;
  height: 0;
  border-top: 9px solid transparent;
  border-right: 8px solid #FFFFFF;
  border-bottom: 9px solid transparent;
  transform: translateY(-50%);
}

.text-item-right {
  justify-content: flex-end;
}
.text-item-right .chat-box {
  margin-left: 0;
  margin-right: 15px;
}
.text-item-right .chat-box:before {
  right: -8px;
  border-left: 8px solid #FFFFFF;
  border-right: none;
}

js-处理拿到的聊天内容(按照个人需求处理)

function getList() {
    const arr = '用户1:嘻嘻嘻嘻嘻。用户2: 你好'.split('\n')
          const arr1 = []
          const nameArr = []
          arr.forEach(i => {
            const list = i.split(':')
               // 找出有几个人-需求只有两个人-因为我们的项目是这样出参的
            if (nameArr.indexOf(list[0]) === -1) {
              nameArr.push(list[0])
            }
          })
          arr.map(item => {
            if (item.indexOf(nameArr[0]) > -1) {
              arr1.push({
                name: nameArr[0],
                content: item.slice(4),
                position: 'left' // 设置是左边框还是右边框
              })
            } else if (item.indexOf(nameArr[1]) > -1) {
              arr1.push({
                name: nameArr[1],
                content: item.slice(4),
                position: 'right'
              })
            }
          })
          this.textList = arr1
}

效果图:

猜你喜欢

转载自blog.csdn.net/momo_mom177/article/details/127447600
今日推荐