【vue】el-input textarea高亮显示问题

问题:

在使用element-ui和vue进行开发时,引入了<el-input type="textarea"></el-input>,用于展示一个xml文件数据,且该xml数据从接口返回时,带有格式,例如:\r\n\t等。在对该textarea进行选择复制功能开发时,发现根据selectionStart和selectionEnd选择的文本,复制结果与选择文本不相同。

解决办法:

问题出现的原因:

原生dom的<textarea></textarea>中,xml的换行符,会被换为\n,该\n的length为1;

而在<el-input>中,xml的换行符为\r\n,该\r\n的length为2。、

所以导致,同样的selectionStart和selectionEnd,高亮显示的文本却不相同。

由于该问题留言人较多,老代码已找不到,因此重新复现该问题,现已重新解决。解决后的效果如下:

 选中文本与获取到的文本完全相同。

具体解决代码如下,原因已在注释中进行说明:

<template>
  <div class="hello">
    <el-input
      id="myText"
      type="textarea"
      :rows="20"
      placeholder="请输入内容"
      v-model="textarea"
      @click.native="textareaClick"
    >
    </el-input>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      textarea: "",
    };
  },
  mounted() {
    let _this = this;
    this.$http
      .get("./static/logback.xml")
      .then(function (res) {
        _this.textarea = res.data;
      })
      .catch((err) => {
        console.log(err);
      });
  },
  methods: {
    textareaClick() {
      let selText = this.getSelectText('myText')
      console.log('选中文本为:' + selText)
    },
    getSelectText(id) {
      var t = document.getElementById(id);
      if (window.getSelection) {
        if (t.selectionStart != undefined && t.selectionEnd != undefined) {
        //使用t.value重新获取当前组件中的值,根据光标起始位置和结束位置进行截取,截取内容和选中内容相同
          return t.value.substring(t.selectionStart, t.selectionEnd); 
          //使用this.textarea的值,根据光标起始位置和结束位置进行截取,截取内容和选中内容不符合
          // return this.textarea.substring(t.selectionStart, t.selectionEnd); 
        } else {
          return "";
        }
      } else {
        return document.selection.createRange().text;
      }
    },
  },
};
</script>

<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值