javascript contenteditable:将光标设置在字符偏移处 [英] javascript contenteditable: set cursor at character offset

查看:198
本文介绍了javascript contenteditable:将光标设置在字符偏移处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将光标设置在特定的字符偏移处。在下面的示例中,我想例如将其设置在 a和 b之间。

I need to set the cursor at a specific character offset. In the example below, I'd want to, for example, set it between the "a" and the "b".

<ul contenteditable = true >
    <li id = "test">abcdef</li>
</ul>

我之前问过这个小提琴: http://jsfiddle.net/5a9uD/1/

I asked before and got this fiddle: http://jsfiddle.net/5a9uD/1/

在给定的示例中效果很好,并且因为那时我需要它。但是它不适用于此示例: http://jsfiddle.net/mdwWN/ 它在以下位置获取IndexSizeError

That worked great for the given example and for what I needed it for then. But it does not work with this example: http://jsfiddle.net/mdwWN/ It gets an IndexSizeError at

range   = sel.getRangeAt(0);


推荐答案

您只需要传递文本容器的 childNodes [0] range.setStart 函数。
检查一下。

You just have to pass text container's childNodes[0] to range.setStart function. Check this out.

function setSelectionRange(aNode, childElem, aOffset) {

  aNode.focus();

  var sel = window.getSelection(),
  range = sel.getRangeAt(0);

  range.collapse(true);

  range.setStart(childElem.childNodes[0], aOffset),

  sel.removeAllRanges();
  sel.addRange(range);
}

var container = document.getElementById("test");
var childElement = document.getElementById('item1');
setSelectionRange(container, childElement, 1);

这是工作的小提琴

这篇关于javascript contenteditable:将光标设置在字符偏移处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆