关于模拟微信聊天框实现

我们知道,微信的聊天框是可以输入图片和文字并存的。其实很简单,只要给div赋予 contenteditable="true" 属性就可以编辑div的内容,话不多说直接贴代码。

预览(样式较丑望忽略):

image.png

代码:

<template>
  <div class="out-box">
    <div class="main">
      <div class="rich-box" contenteditable="true" ref="is_rich"></div>
      <div class="btn-box">
        <div class="button send" @click="subShow(0)">发送</div>
        <div class="button review" @click="subShow(1)">回复</div>
      </div>
    </div>
    <div class="msg-box">
      <div class="content-box" v-for="item in contents" :style="{ justifyContent: item.idx == 0? 'flex-end' : 'flex-start' }">
        <div :class="['show-box', item.idx == 0? 'left' : 'right']" v-html="item.content"></div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "chat",
    data() {
      return {
        contents: []
      }
    },
    methods: {
      subShow(idx) {
        this.contents.push({ idx: idx, content: this.$refs.is_rich.innerHTML })
        this.$refs.is_rich.innerHTML = ''
      }
    }
  }
</script>

<style scoped>
  .out-box {
    display: flex;
    justify-content: space-between;
  }
  .main {
    width: auto;
    height: auto;
  }
  .main span {
    display: block;
    padding: 10px 0;
  }
  .rich-box {
    width: 600px;
    height: 50vh;
    position: relative;
    overflow: scroll;
    border: 1px solid black;
    padding: 20px;
    background: white;
  }
  .rich-box>>>img {
    width: auto;
    height: 100px;
    object-fit: contain;
  }
  .btn-box {
    width: 240px;
    display: flex;
    margin: 0 auto;
  }
  .button {
    width: 100px;
    height: 30px;
    border-radius: 5px;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
    transition: all 300ms;
    border: 1px solid black;
    margin: 5px auto;
    color: white;
  }
  .send {
    background: #009aff;
  }
  .review {
    background: darkorange;
  }
  .msg-box {
    width: 600px;
    height: 50vh;
    overflow: scroll;
    border: 1px solid black;
    padding: 20px;
    background: white;
  }
  .content-box {
    display: flex;
    margin: 5px;
  }
  .show-box {
    width:fit-content;
    height: auto;
    position: relative;
    padding: 10px 10px;
    border-radius: 5px;
    background: rgb(102, 215, 97);
  }
  .left {
    background: rgb(102, 215, 97);
    justify-content: left;
  }
  .right {
    background: rgb(196, 196, 196);
    justify-content: right;
  }
  .show-box>>>img {
    width: auto;
    height: 100px;
    object-fit: contain;
    padding: 5px;
  }
</style>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容