单击按钮在文本框中添加占位符



我有一个文本框

<div>
<b-form-textarea
id="textarea"
v-model="text"
placeholder="Certification text "
rows="5"
max-rows="6"
></b-form-textarea>
</div>  

和两个按钮

<b-button variant="primary" class="btn btn-primary btn-lg top-right-button mr-1">Save</b-button>
<b-button variant="info" class="btn btn-info btn-lg top-right-button mr-1">Add Name</b-button>

当用户在键入时,如果他单击"添加名称"按钮,则应将{名称}放置在文本框中(光标所在的位置(。我该如何实现它?

您可以将ref添加到文本区域,并访问包含光标位置的selectionStart属性。然后,您可以使用此索引将给定的文本拼接到给定位置的文本区域的文本中。

由于单击该按钮将失去输入的焦点,您可以通过在ref上调用focus方法,以及设置selectionStartselectionEnd,将其添加回来,使光标位于其停止的位置。

new Vue({
el: "#app",
data() {
return {
text: ""
};
},
methods: {
addName() {
const { text } = this;
const textarea = this.$refs["my-textarea"].$el;
const index = textarea.selectionStart;
const name = "{name}";
this.text = `${text.substring(0, index)}${name}${text.substring(
index
)}`;
textarea.focus();
setTimeout(() => {
textarea.selectionStart = index + name.length;
textarea.selectionEnd = index + name.length;
});
}
}
});
<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.17.3/dist/bootstrap-vue.js"></script>
<link href="https://unpkg.com/bootstrap@4.5.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap-vue@2.17.3/dist/bootstrap-vue.css" rel="stylesheet" />
<div id="app">
<b-form-textarea ref="my-textarea" v-model="text" placeholder="Certification text" rows="5" max-rows="6">
</b-form-textarea>
<b-btn variant="primary" size="lg" @click="addName">
Add Name
</b-btn>
</div>

最新更新