對於那些誰沒有與谷歌文檔編輯器,在這裏工作是它如何工作的一個簡短的解釋:如何在Google文檔中衡量單詞/插入符的位置?
- 谷歌文檔是不可見的可編輯的文本區域或CONTENTEDITABLE元素。
- 谷歌文檔在單獨的iFrame中監聽keydown/press/up,在這裏他們放置OS光標以進行事件監聽。
- 當iFrame通過對可見文檔執行等效操作來捕獲Google處理它的事件時。
- Google Docs中的「caret」是一個DIV,它的樣式和腳本可以像OS遊標一樣進行查看和操作。
有了這樣的方式,這是我的要求:
我的工作是與谷歌文檔進行交互的插件,我需要能夠做兩件事情:
- 用不透明疊加DIV突出顯示單詞。
- 確定單詞內的光標位置。
我已經用盡了很多關於只是如何處理這種想法,但到目前爲止,我只弄到後面的問題(我執行回退一車解決方案,確定在文本改變並撤消退格)。
我正在尋找所有可以提出來解決這些問題的最佳創意。他們不需要跨瀏覽器,但他們確實需要能夠變成強大的東西,以處理諸如字體大小改變中線等事情。
的額外的信息解釋谷歌文檔看起來像在HTML一點點:
<wrapper> // Simplified wrapper containing margins, pagination and similar
<div class="kix-paragraphrenderer"> // single DIV per page wrapping all content
// Multiple paragraphs separated by linebreak created by Enter key:
<div class="kix-paragraphrendeder">...</div>
<div class="kix-paragraphrendeder">...</div>
<div class="kix-paragraphrendeder">
// Multiple wrapper divs created by Google's word wrapping:
<div class="kix-lineview">...</div>
<div class="kix-lineview">...</div>
<div class="kix-lineview">
// Single inner wrapper, still full width of first wrapper paragraph:
<div class="kix-lineview-content">
// Single wrapper SPAN containing full text of the line, but not display:block
<span class="kix-lineview-text-block">
// Multiple spans, one per new font change such as normal/bold text,
// change in font size, indentation and similar:
<span>This is normal text</span>
<span style="font-size:40px; padding-left:4px;">This larger text.</span>
<span style="font-weight:bold; padding-left:10px;">This is bold text</span>
<span style="padding-left:4px;">More normal text</span>
</span>
</div>
</div>
</div>
</div>
</wrapper>
不確定我是否按照你的意思替換'textNode',但自從我的答案我更新了我的代碼,以執行類似於你的建議。與改變任何HTML相反,我創建了一個Range對象並操縱開始和結束節點,直到Range.getBoundingClientRect()可以通過與cursor.getBoundingClientRect()進行比較來告訴我光標所在的位置。 – Woodgnome 2014-01-30 16:11:29