Skip to content

Instantly share code, notes, and snippets.

@Janking
Last active April 30, 2016 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Janking/2a2a8c7dfbc620ac0dc00f169febd7ad to your computer and use it in GitHub Desktop.
Save Janking/2a2a8c7dfbc620ac0dc00f169febd7ad to your computer and use it in GitHub Desktop.
var el = document.getElementById("editable"); // 获取编辑器元素
var range = document.createRange(); // 创建 range 对象
var sel = window.getSelection(); // 创建 selection 对象
range.setStart(el.childNodes[2], 5); // 设置光标位置
range.collapse(true); // 折叠(闭合)range的端
sel.removeAllRanges(); // 清空 selection 对象中的所有 range
sel.addRange(range); // 插入光标的range
el.focus();
// 具体思路:先定义好光标位置,并为光标创建一个range对象,然后插入到selection对象中。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment