Vue自动获取焦点并且光标移至最后

  • Post author:
  • Post category:vue



项目需求 :

每次进入页面时,需要

自动聚焦

到一个文本框上,让其右侧的设置面板显现出来。

( 这里之所以 p 标签可以进行聚焦是因为其设置了

contenteditable



true

了 )

并且

光标

最好是自动移至到最后面,优化用户的体验。


代码实现 :

<template>
  <div>
    <p id="noteInput" v-html="text" contenteditable="true"></p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: "hello_World",
    };
  },
  mounted() {
    // 每次进入页面, 自动获取到 p 标签内的焦点, 光标移至最后
    this.$nextTick(() => {
      let notesDom = document.getElementById("noteInput");
      if (window.getSelection) {
        // 兼容 IE11 10 9 ff safari
        // notesDom.focus(); // 解决ff不获取焦点无法定位问题
        let range = window.getSelection(); // 创建range
        range.selectAllChildren(notesDom); // range 选择notesDom下所有子内容
        range.collapseToEnd(); // 光标移至最后
      } else if (document.selection) {
        // 兼容 IE10 9 8 7 6
        let range = document.selection.createRange(); // 创建选择对象
        range.moveToElementText(notesDom); // range定位到notesDom
        range.collapse(false); // 光标移至最后
        range.select();
      }
    });
  },
};
</script>


函数封装 :

/**
 * 解决标签设置 contenteditable 为 true 时,获取焦点后光标位置放在最后
 * @param {*} obj 传入的聚焦对象
 */
const keepLastIndex = (obj) => {
  console.log(obj)
  console.log(window.getSelection)
  console.log(document.selection)
  if (window.getSelection) { // 兼容 IE11 10 9 ff safari
    obj.focus(); // 解决 ff 不获取焦点 无法定位问题
    let range = window.getSelection(); // 创建 range
    range.selectAllChildren(obj); // range 选择 obj 下所有子内容
    range.collapseToEnd(); // 光标移至最后
  } else if (document.selection) { // 兼容 IE10 9 8 7 6 5
    let range = document.selection.createRange(); // 创建选择对象
    // var range = document.body.createTextRange();
    range.moveToElementText(obj); // range 定位到 obj
    range.collapse(false); // 光标移至最后
    range.select();
  }
}

在实际使用时 , vue.$emit 是一个 异步函数 , 最好在调用这个定位前加上一定的延迟 ,

经测试 , 5 ms 就可以了

import { keepLastIndex } from '@/utils/tools'

  mounted() {
    setTimeout(() => {
      keepLastIndex(e.target);
    }, 5);

    // 或者

    this.$nextTick(() => {
      // keepLastIndex(e.target);
      let notesDom = document.getElementById('noteInput')
      keepLastIndex(notesDom)
    });
  }



版权声明:本文为weixin_58099903原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。