预览截图:
demo详细代码:https://gitee.com/mosmos_admin/wxemoji
引入js:emoji-parser.esm.js
页面操作:
// 表情组件
const emojiParser = require("../components/emoji/emoji-parser.esm");
Page({
data: {
// 获取表情
emojis:emojiParser.getEmojis({ size: 30 }),
// 输入内容
text:"",
// 光标位置
textCursor:0,
// 用于显示的内容
textEle:"",
},
inputText: function (e) {
let value = e.detail.value;
var textEle = emojiParser.parseEmoji(value);
this.setData({
text: value,
textEle:textEle
})
},
textBlur:function(e){
this.setData({
textCursor:e.detail.cursor,
})
},
textInsertEmoji:function(e){
var _that = this;
// 延时只是为了让textarea先失去焦点,以便获取光标位置
setTimeout(function(){
var name = e.currentTarget.dataset.name;
var length = name.length;
var textCursor = _that.data.textCursor;
var text = _that.data.text;
var newText = text.slice(0,textCursor)+ name +text.slice(textCursor);
var textEle = emojiParser.parseEmoji(newText);
_that.setData({
text:newText,
textCursor:textCursor+length,
textEle:textEle
})
},100)
},
onLoad() {
// 设置显示结果的表情大小
emojiParser.configParseEmoji({ size: 30 })
},
})
页面:
<view style="width:100%;height:100%;">
<view style="padding:0 20px;">
<textarea value="{{text}}" bindinput="inputText" bindfocus="textFocus" bindblur="textBlur" placeholder="输入测试"></textarea>
</view>
<view style="padding:0 20px;height:200px;overflow:scroll;">
<block wx:for="{{emojis}}" wx:key="index">
<view class="emotion_item" data-name="{{item.cn}}" bindtap="textInsertEmoji">
<view class="icon_emotion" style="{{item.style}}"></view>
</view>
</block>
</view>
<view style="padding:20px;">
显示结果:
<rich-text nodes="{{'<div style=\"white-space: pre-line;\">'+ textEle +'</div>'}}"></rich-text>
</view>
</view>