写html代码,使用element 做一个按钮,点击一下,在textarea里光标所在位置,增加一个字符串
时间: 2024-03-15 16:47:59 浏览: 14
好的,以下是使用element库创建一个按钮,点击后在textarea中插入字符串的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>按钮插入字符串</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" />
</head>
<body>
<div id="app">
<el-input type="textarea" v-model="text"></el-input>
<el-button @click="insertStr">插入字符串</el-button>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
text: ""
};
},
methods: {
insertStr() {
const textarea = document.querySelector("textarea");
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const str = "要插入的字符串";
this.text = this.text.substring(0, start) + str + this.text.substring(end);
textarea.focus();
textarea.selectionStart = start + str.length;
textarea.selectionEnd = start + str.length;
}
}
});
</script>
</body>
</html>
```
这里使用了Vue和Element库,首先创建一个包含textarea和按钮的页面,并且使用v-model指令将textarea的内容绑定到data中的text变量上。点击按钮时,会调用insertStr方法,在该方法中获取textarea的光标位置,然后在text中插入字符串,最后再将光标移动到插入字符串后面。
需要注意的是,这里的textarea是使用Element库中的el-input组件实现的,所以需要通过querySelector方法获取到textarea元素才能进行插入操作。