最近遇到一个需要是聊天添加表情功能,本来很简单,点就表情追加到input内容里即可。
但是表情只能追加到字符串最后面,这就很恼火。
有没有办法在光标制定位置插入呢?当然有,只不过小程序做法和H5略有区别,这里两种都介绍一下。
首先是H5
这里我直接抛出代码,原理也很简单,主要利用的是input和textarea中的setSelectionRange属性获取光标位置。这里不做过多解释,主要看下小程序1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function setCaret(textObj) {
if (textObj.createTextRange) {
textObj.caretPos = document.selection.createRange().duplicate();
}
}
function insertAtCaret(textObj, textFeildValue) {
if (document.all) {
if (textObj.createTextRange && textObj.caretPos) {
var caretPos = textObj.caretPos;
caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? textFeildValue + ' ' : textFeildValue;
} else {
textObj.value = textFeildValue;
}
} else {
console.log(1)
if (textObj.setSelectionRange) {
var rangeStart = textObj.selectionStart;
var rangeEnd = textObj.selectionEnd;
var tempStr1 = textObj.value.substring(0, rangeStart);
var tempStr2 = textObj.value.substring(rangeEnd);
textObj.value = tempStr1 + textFeildValue + tempStr2;
} else {
alert("This version of Mozilla based browser does not support setSelectionRange");
}
}
}
</script>
<form id="form1" action="" onsubmit="" method="post" enctype="text/plain">
<p>
<textarea id="textarea" name="tarea" rows="" cols="" style="width:300px;height:120px;"
onselect="setCaret(this);" onclick="setCaret(this);" onkeyup="setCaret(this);">例子例子例子例子例子</textarea>
<br /><br />
<input type="text" name="textfield" style="width:220px;" value="插入FireFox" />
<br />
<input type="button" value="插入" onclick="insertAtCaret(this.form.tarea,this.form.textfield.value);" />
</p>
</form>
<div id="box" contenteditable="true" style="border:1px solid #ccc; width:300px; height:200px;">sljfldjfldf</div>
</body>
</html>
小程序
小程序需要在textarea或input中绑定失焦事件bindblur="onBlur"
1
<textarea id="textarea" auto-focus="true" placeholder="请输入文章内容" value="{{content}}" bindinput="onInput" bindblur="onBlur"/>
然后在失焦事件获取失焦时光标的位置,即光标在文本域中的下标1
2
3
4
5onBlur(e) {
this.setData({
cursor: e.detail.cursor
})
},
然后在插入表情的实践中将表情插入文本域字符串中(也就是表情的点击事件中)1
2
3
4
5
6
7
8inputGif(e) {
const index = e.currentTarget.dataset.index
setTimeout(() => {
this.setData({
content: this.data.content.slice(0, this.data.cursor) + this.data.gif[index].code + this.data.content.slice(this.data.cursor)
})
}, 100)
},
这里我使用了setTimeout
延时了100ms执行,原因是如果执行,失焦实践是在点击事件之后触发的,就会出现插入的位置是上一次失焦时的位置,所以需要插入时延迟100ms先让文本域失焦并设置好光标位置,再执行插入。
至此小程序的光标制定位置插入内容就完成了,有木有很简单。