如何在contenteditable div中的跨度中设置光标位置 [英] How to set cursor position in span in contenteditable div

查看:62
本文介绍了如何在contenteditable div中的跨度中设置光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码是我现在使用的代码,只是将光标位置设置为span的尾部

The code below is what I use now, just to set the cursor position to the tail of span

var node = document.getElementById("span_first");
var range = document.createRange();  
range.setStartAfter(node);
var sel = window.getSelection();
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);

http://jsfiddle.net/vXnCM/3837/

但是我想将光标位置设置在跨度中的任何位置,该怎么办?

But I want to set the cursor position at any place in the span, how can I do?

谢谢.

推荐答案

您可以这样做:

function setCaret() {
   var element = document.getElementById("input");
   var range = document.createRange();  
   var node;   
   node = document.getElementById("first");  
   range.setStart(node.childNodes[0], 1);  <-- sets the location 
   var sel = window.getSelection();
   range.collapse(true);
   sel.removeAllRanges();
   sel.addRange(range);
   element.focus();    
}

node.childNodes []与要在其上设置光标的行有关,下一个数字是该行的位置.在此示例中,将空间1移动到第0行(实际上是第1行).因此,如果您将这些值更改为变量并将其作为参数放入函数中,则可以指定位置.

node.childNodes[] pertains to which line you want to set the cursor on and the next number is the location on that line. In this example is moves to space 1 line 0 (line 1 really). So if you change those values to variables and put them as parameters in your function you could specify where.

这篇关于如何在contenteditable div中的跨度中设置光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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