js实现替换输入框中选中的文字

如果已知一个文本框内输入值,想点击替换掉里面选中的值,可以采用以下方法;
其实就是获取到选中的开始结束为止,然后使用subString方法进行切割字符串即可

javascript 复制代码
<template>
  <div>
    <el-input v-model="mobileText" ref="input"></el-input>
    <el-button @click="replaceSelection">替换选中文字</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      mobileText: '这是一段示例文本。',
      selectionStart: 0,
      selectionEnd: 0,
    };
  },
  methods: {
    // 获取选中的文字的起始和结束位置
    handleSelection() {
      this.selectionStart = this.$refs.input.selectionStart;
      this.selectionEnd = this.$refs.input.selectionEnd;
    },
    replaceSelection() {
      // 获取选中的文字
      const selectedText = this.mobileText.substring(this.selectionStart, this.selectionEnd);
      // 替换选中的文字,这里以"新内容"为例
      const newText = this.mobileText.substring(0, this.selectionStart) + "新内容" + this.mobileText.substring(this.selectionEnd);
      // 更新数据模型中的文本
      this.mobileText = newText;
    }
  }
}
</script>
相关推荐
摘星编程13 分钟前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe55616 分钟前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-202229 分钟前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程29 分钟前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js
lili-felicity32 分钟前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos
济6171 小时前
linux 系统移植(第六期)--Uboot移植(5)--bootcmd 和 bootargs 环境变量-- Ubuntu20.04
java·前端·javascript
lili-felicity1 小时前
React Native for OpenHarmony 实战:Easing 动画完全指南
javascript·react native·react.js
持续前行2 小时前
vscode 中找settings.json 配置
前端·javascript·vue.js
JosieBook2 小时前
【Vue】11 Vue技术——Vue 中的事件处理详解
前端·javascript·vue.js
韩曙亮2 小时前
【jQuery】jQuery 简介 ( JavaScript 库简介 | jQuery 核心概念、特点 | jQuery 下载并使用 )
前端·javascript·jquery