2013-05-26 56 views
1

我有以下的HTML:使用Javascript/jQuery的:如何在ID設置焦點內CONTENTEDITABLE

<div id="content" contenteditable="true" style="font-family: Helvetica;"> 
    Some text 
    <div id="cursor" contenteditable="true"></div> 
    Some other text. 
</div> 

現在我想一些文字(恰好#cursor)後設置光標。我試過兩種方式:

$('#cursor').focus(); 
document.getElementById('#cursor').focus(); 

但它沒有工作。有沒有辦法做到這一點?

+0

能否請你解釋一下你是什麼意思時說'設置光標'? –

+0

dup:http://stackoverflow.com/questions/14449721/set-cursor-position-after-nested-contenteditable – JNF

回答

2

#content是外部編輯元素,所以你需要關注的是,並將光標移動內部#cursor,但由於#cursor沒有內容,沒有什麼目標的選擇。一個解決辦法是增加一些內容進行定位,就像一個textNode,移動插入符號,然後刪除該內容,就像這樣:

var el = document.getElementById("content"), 
    el2 = document.getElementById("cursor"), 
    range = document.createRange(), 
    sel = window.getSelection(); 

el2.innerHTML="temp"; 
var t = el2.childNodes[0]; 

range.setStartBefore(t); 
range.collapse(true); 
sel.removeAllRanges(); 
sel.addRange(range); 
el.focus(); 
el2.innerHTML = ""; 

FIDDLE

+2

不適用於Firefox,並且Chrome沒有閃爍的插入符號。 – giorgio79

+0

可以確認它在Firefox中不起作用。 – 2014-11-07 00:33:42