【微信小程序】实现聊天功能完整实例代码附效果图和注释

GIwqwqF.gif

下面是完整代码,可以实现发送以后自动把屏幕的焦点放在最后一条信息

<view class='tab'>
  <view class='lan'>{{tabdata.title}}</view>
  <view class='tent'>
    <text>{{tabdata.attribute_attribute}}</text>
    <text class='fl_r '>{{tabdata.num}}</text>
  </view>
  <view class='xiahuaxian1'></view>
  <view>
    <text class='fabu'>发布时间: {{tabdata.time_agree}}</text>
  </view>
</view>
<view class='news'>
  <view class='xiahuaxian1 xiahuaxia'></view>
  <view class='new_top_txt'>您正在与{{tabdata.nickname}}进行沟通</view>
  <view class="historycon">
    <scroll-view scroll-y="true" scroll-top="{{scrollTop}}" class="history" wx:for="{{centendata}}" wx:key=''>
      <view>
        <text class='time'>{{item.time}}</text>
      </view>
      <block wx:if="{{item.is_show_right ==1}}">
        <view class='my_right'>
          <view class='page_row'>
            <text wx:if='{{!item.is_img}}' class='new_txt'>{{item.content}}</text>
            <image wx:if='{{item.is_img}}' src='{{item.content}}' class='new_imgtent'></image>
            <view wx:if='{{!item.is_img}}' class='sanjiao my'></view>
            <image class='new_img' wx:if='{{item.show_rignt == "是自己的内容,显示在右边,右边渲染 nickname_owner,head_owner"}}' src='{{item.head_owner}}'></image>
             <image class='new_img' wx:if='{{item.show_rignt == "是自己的内容,显示在右边,右边渲染 nickname_open,head_open"}}' src='{{item.head_open}}'></image>
          </view>
        </view>
      </block>
      <block wx:else>
        <view class='you_left'>
          <view class='page_row'>
            <image class='new_img' wx:if='{{item.show_rignt == "不是自己的内容,显示在左边,左边渲染 nickname_owner,head_owner"}}' src='{{item.head_owner}}'></image>
             <image class='new_img' wx:if='{{item.show_rignt == "不是自己的内容,显示在左边,左边渲染 nickname_open,head_open"}}' src='{{item.head_open}}'></image>
            <view wx:if='{{!item.is_img}}' class='sanjiao you'></view>
            <text wx:if='{{!item.is_img}}' class='new_txt'>{{item.content}}</text>
            <image wx:if='{{item.is_img}}' src='{{item.content}}' class='new_imgtent'></image>
          </view>
        </view>
      </block>
    </scroll-view>
  </view>
</view>
<view class='hei' id="hei"></view>
<view class="sendmessage">
  <input type="emoji" bindinput="bindChange" confirm-type="done" value='{{news_input_val}}' placeholder="" />
  <button catchtap="add">发送</button>
  <input style='display:none' type="" bindinput="bindChange" confirm-type="done" placeholder="" />
  <image bindtap="upimg1" class='jia_img' src='../../../images/jia_img.png'></image>
</view>```
```// pages/index/to_news/to_news.js
var app = getApp();
var util = require("../../../utils/util.js")
var message = '';
var text = '';
var user = {};
var length;
var zx_info_id;
var openid_talk;
Page({
  data: {
    news: '',
    scrollTop: 0,
    message: '',
    text: text,
    centendata: '',
    nickName: '',
    avatarUrl: '',
    news_input_val:'',
    tabdata: ''
  },
  bindChange: function (e) {
    message = e.detail.value
  },
  //事件处理函数
  add: function (e) {
    var that = this
    var data = {
      program_id: app.jtappid,
      openid: app._openid,
      zx_info_id: zx_info_id,
      content: message,
      openid_talk:openid_talk
    }
    util.request('/session_submit', 'post', data, '正在加载数据', function (res) {
      if (res.data.state == 1) {
        var a = true;
        that.loaddata(a);
        that.setData({
          news_input_val:''
        })
        message = ''
      } else {
        wx.showToast({
          title: '网络错误,请稍后',
        })
      }
    })
  },

  onLoad: function (options) {
    openid_talk = options.openid_talk;
    zx_info_id = options.zx_info_id;
    console.log(openid_talk)
    //调用应用实例的方法获取全局数据
    this.setData({
      zx_info_id: zx_info_id,
      nickName: app.nickName,
      avatarUrl: app.avatarUrl,
    });
    this.loaddata()
  },
  // 页面加载
  loaddata: function (a) {
    var that = this;
    var is_img = true;
    var data = {
      program_id: app.jtappid,
      openid: app._openid,
      zx_info_id: zx_info_id,
      openid_talk: openid_talk
    }
    util.request('/session_page', 'post', data, '', function (res) {
      if (res.data.k1) {
        res.data.k1.time_agree = util.js_date_time(res.data.k1.time_agree)
      }
      for (var i = 0; i < res.data.k2.length; i++) {
        res.data.k2[i].time = util.js_date_time(res.data.k2[i].time)
        var n = res.data.k2[i].content.charAt(res.data.k2[i].content.length - 1);
        switch (n) {
          case 'g':
            res.data.k2[i].is_img = is_img
            break;
          default:
        }
      }
      that.setData({
        tabdata: res.data.k1,
        centendata: res.data.k2.reverse()
      })
      wx.setNavigationBarTitle({ title: that.data.tabdata.nickname });
      if (a) {
        setTimeout(function () {
            that.bottom()
        }, 500);
      }
    })
    setTimeout(function () {
      if (that.data.centendata.length != length) {
        length = that.data.centendata.length
      }
      that.loaddata()
    }, 3000);
    
  },
  // 获取hei的id节点然后屏幕焦点调转到这个节点
  bottom: function () {
    var query = wx.createSelectorQuery()
    query.select('#hei').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      wx.pageScrollTo({
        scrollTop: res[0].bottom  // #the-id节点的下边界坐标
      })
      res[1].scrollTop // 显示区域的竖直滚动位置
    })
  },
  // 选择图片并把图片保存  
  upimg1: function () {
    var that = this;
    wx.chooseImage({
      success: function (res) {
        var data = {
          program_id: app.jtappid,
          openid: app._openid,
          zx_info_id: zx_info_id,
        }
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: '/session_submit', //提交信息至后台
          filePath: tempFilePaths[0],
          name: 'content', //文件对应的参数名字(key)
          formData: data,  //其它的表单信息
          success: function (res) {
            var a = true;
            that.loaddata(a);
            message = ''
          }
        })
      }
    })
  }
})```

```/* pages/index/to_news/to_news.wxss */

page {
  background-color: #f7f7f7;
}

.tab {
  padding: 20rpx 20rpx 40rpx 50rpx;
  height: 20%;
  background-color: white;
}

.tab .tent {
  font-size: 33rpx;
  margin-bottom: 30rpx;
}
.jia_img{
  height: 80rpx;
  width: 90rpx;
}
.new_imgtent{
    height: 180rpx;
  width: 190rpx;
}
.tab .fabu {
  font-size: 33rpx;
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}

.xiahuaxia {
  width: 80%;
  text-align: center;
  margin: 0 auto;
  position: relative;
  top: 60rpx;
}

.time {
  text-align: center;
  padding: 5rpx 20rpx 5rpx 20rpx;
  width: 200rpx;
  font-size: 26rpx;
  background-color: #E8E8E8;
}

.new_top_txt {
  width: 50%;
  position: relative;
  top: 38rpx;
  text-align: center;
  margin: 0 auto;
  font-size: 30rpx;
  color: #787878;
  background-color: #f7f7f7;
}

/* 聊天内容 */

.news {
  margin-top: 30rpx;
  text-align: center;
  margin-bottom: 150rpx;
}

.img_null {
  height: 60rpx;
}

.l {
  height: 5rpx;
  width: 20%;
  margin-top: 30rpx;
  color: #000;
}

/* 聊天 */

.my_right {
  float: right;
  position: relative;
  right: 40rpx;
}

.you_left {
  float: left;
  position: relative;
  left: 5rpx;
}

.new_img {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
}

.new_txt {
  width: 380rpx;
  border-radius: 7px;
  background-color: #95d4ff;
  padding: 0rpx 30rpx 0rpx 30rpx;
}

.sanjiao {
  top: 20rpx;
  position: relative;
  width: 0px;
  height: 0px;
  border-width: 10px;
  border-style: solid;
}

.my {
  border-color: transparent transparent transparent #95d4ff;
}

.you {
  border-color: transparent #95d4ff transparent transparent;
}

.sendmessage {
  background-color: white;
  width: 100%;
  position: fixed;
  bottom: 0rpx;
  display: flex;
  flex-direction: row;
}

.sendmessage input {
  width: 80%;
  height: 40px;
  background-color: white;
  line-height: 40px;
  font-size: 14px;
  border: 1px solid #d0d0d0;
  padding-left: 10px;
}

.sendmessage button {
  border: 1px solid white;
  width: 18%;
  height: 40px;
  background: #fff;
  color: #000;
  line-height: 40px;
  font-size: 14px;
}

.historycon {
  height: 90%;
  width: 100%;
  flex-direction: column;
  display: flex;
  margin-top: 100rpx;
  border-top: 0px;
}
.hei{
  margin-top: 50px;
  height: 20rpx;
}
.history {
  height: 100%;
  margin-top: 15px;
  margin: 10px;
  font-size: 14px;
  line-height: 40px;
  word-break: break-all;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容