Vue中div contenteditable 的光标定位方法
作者:CloudJay_喵喵喵 时间:2024-05-28 15:58:17
在Vue做项目时,做了一个div[contenteditable=true]的组件作为文本输入框
在非手动输入值后,光标会丢失,经测试以下这段代码可用,直接将光标定位到最后
function keepLastIndex(obj) {
console.log(obj)
console.log(window.getSelection)
console.log(document.selection)
if (window.getSelection) { //ie11 10 9 ff safari
obj.focus(); //解决ff不获取焦点无法定位问题
var range = window.getSelection(); //创建range
range.selectAllChildren(obj); //range 选择obj下所有子内容
range.collapseToEnd(); //光标移至最后
} else if (document.selection) { //ie10 9 8 7 6 5
var range = document.selection.createRange(); //创建选择对象
//var range = document.body.createTextRange();
range.moveToElementText(obj); //range定位到obj
range.collapse(false); //光标移至最后
range.select();
}
}
在实际使用时,vue.$emit是一个异步函数,最好在调用这个定位前加上一定的延迟,经测试,5ms就可以了
setTimeout(()=>{
keepLastIndex(e.target)
},5)
来源:https://blog.csdn.net/qq_31061615/article/details/80263746
标签:Vue,div,contenteditable,光标
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
js的Prototype属性解释及常用方法
2024-06-07 16:00:32
![](https://img.aspxhome.com/file/2023/4/122144_0s.gif)
树型结构在ASP中的简单解决
2007-10-07 12:52:00
python实现上传文件到linux指定目录的方法
2023-02-05 03:03:56
![](https://img.aspxhome.com/file/2023/9/120349_0s.png)
Python手绘可视化工具cutecharts使用实例
2022-12-25 07:27:54
![](https://img.aspxhome.com/file/2023/3/121403_0s.png)
用 SA FileUp 上传多文件
2008-07-04 13:44:00
python实现过滤敏感词
2021-02-26 04:23:17
![](https://img.aspxhome.com/file/2023/4/93614_0s.png)
SQL判断字段列是否存在的方法
2024-01-22 16:30:26
python安装scipy的方法步骤
2022-02-27 21:10:45
![](https://img.aspxhome.com/file/2023/9/131309_0s.png)
对python 中class与变量的使用方法详解
2023-12-27 19:22:10
Windows2012配置SQLServer2014AlwaysOn的图解
2024-01-16 15:39:01
![](https://img.aspxhome.com/file/2023/7/96157_0s.png)
Python实现屏幕截图的两种方式
2023-02-27 03:54:29
详解OpenCV实现特征提取的方法
2022-10-05 11:15:28
![](https://img.aspxhome.com/file/2023/1/76071_0s.jpg)
Python中re.findall()用法详解
2023-08-09 23:46:14
![](https://img.aspxhome.com/file/2023/1/61191_0s.png)
用Python制作一个文件加密器
2023-01-16 02:41:05
![](https://img.aspxhome.com/file/2023/7/102737_0s.jpg)
避免使用滤镜
2009-10-13 20:30:00
django之跨表查询及添加记录的示例代码
2022-11-23 14:44:25
CTF中的PHP特性函数解析之上篇
2023-06-14 02:19:58
![](https://img.aspxhome.com/file/2023/8/55518_0s.jpg)
Mysql中的自连接问题
2024-01-17 17:55:43
![](https://img.aspxhome.com/file/2023/8/76358_0s.png)
PHP实现的微信公众号扫码模拟登录功能示例
2023-11-22 18:13:08
解析mysql修改为utf8后仍然有乱码的问题
2024-01-14 14:36:09