vue获取textarea 光标的位置并插入文字
vue不是用UI框架textearehtml<textarea v-model="content" id="textarea" type="textarea" rows="2" autocomplete="off" style="width: 100%;height: 60px;"></textarea><divstyle="margin-left: 30px;"&g
·
vue不是用UI框架texteare
html
<textarea v-model="content" id="textarea" type="textarea" rows="2" autocomplete="off" style="width: 100%;height: 60px;"></textarea>
<divstyle="margin-left: 30px;">
<ul v-for="(f,i) in friend_list">
<li class="nameList" @click="insertAtCursor(f.name)">{{f.name}}</li>
</ul>
</div>
script
new Vue({
el: '#app',
data: {
content: '',
friend_list: [{
name: "【QQ音乐】",
}, {
name: "【网易云音乐】",
}, {
name: "【酷狗音乐】",
}, {
name: "【酷我音乐】",
}, {
name: "【哔哩哔哩】",
}, {
name: "【咪咕音乐】",
}, {
name: "【千千音乐】"
}],
},
methods: {
async insertAtCursor(myValue) {
const myField = document.querySelector('#textarea')
if (myField.selectionStart || myField.selectionStart === 0) {
var startPos = myField.selectionStart
var endPos = myField.selectionEnd
this.content = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length)
await this.$nextTick() // 这句是重点, 圈起来
myField.focus()
myField.setSelectionRange(endPos + myValue.length, endPos + myValue.length)
} else {
this.content += myValue
}
},
}
})
vue使用了element ui
<el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="content" id="textarea"></el-input>
<div style="margin-left: 30px;">
<ul v-for="(f,i) in friend_list">
<li class="nameList" @click="insertAtCursor(f.name)">{{f.name}}</li>
</ul>
</div>
new Vue({
el: '#app',
data: {
content: '',
friend_list: [{
name: "【QQ音乐】",
}, {
name: "【网易云音乐】",
}, {
name: "【酷狗音乐】",
}, {
name: "【酷我音乐】",
}, {
name: "【哔哩哔哩】",
}, {
name: "【咪咕音乐】",
}, {
name: "【千千音乐】"
}],
},
methods: {
async insertAtCursor(myValue) {
const myField = document.querySelector('#textarea textarea')
if (myField.selectionStart || myField.selectionStart === 0) {
var startPos = myField.selectionStart
var endPos = myField.selectionEnd
this.content = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length)
await this.$nextTick() // 这句是重点, 圈起来
myField.focus()
myField.setSelectionRange(endPos + myValue.length, endPos + myValue.length)
} else {
this.content += myValue
}
},
}
})
效果图
更多推荐
已为社区贡献1条内容
所有评论(0)