一般情况下,我们需要使用一个类似富文本的功能,contenteditable是最轻量好用的功能,但是有时候我们希望页面跳转进来的时候。通过外部组件传入的关键字,跳转到该关键字后面的位置,如下图
比如传入c# 的时候,光标自然定位到c#后面
js 使用contenteditable属性模拟富文本框的时候如何定位光标到指定位置
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- 温水煮蚂蚁 2022-12-01 13:36关注
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style>#edit{height:100px;width:500px;border:1px solid red;}</style> </head> <body> <div id="edit" style="white-space: pre" contenteditable>java c# c++ </div> <input type="text" id="key-word" value="c#"/> <button id="cursor-btn">设置光标位置</button> <script> function cursorAt(el, index) { el.focus(); getSelection().setPosition(el.firstChild, index); } let edit = document.getElementById('edit'); let keyWord = document.getElementById('key-word'); let cursorBtn = document.getElementById('cursor-btn'); cursorBtn.onclick = function() { debugger let index = edit.innerText.indexOf(keyWord.value) + keyWord.value.length; cursorAt(edit, index); } </script> </body> </html>
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用
悬赏问题
- ¥15 谁有desed数据集呀
- ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
- ¥15 关于#hadoop#的问题
- ¥15 (标签-Python|关键词-socket)
- ¥15 keil里为什么main.c定义的函数在it.c调用不了
- ¥50 切换TabTip键盘的输入法
- ¥15 可否在不同线程中调用封装数据库操作的类
- ¥15 微带串馈天线阵列每个阵元宽度计算
- ¥15 keil的map文件中Image component sizes各项意思
- ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏