2012-02-20 78 views
2

我在做一個所見即所得的編輯器,我需要知道如何讓插入位置工作。看來沒有明顯的方式來實現跨平臺。插頁位置跨瀏覽器?

我只需要語法。請不要將我指向Mozilla開發者頁面;我沒有覺得它特別有用。 我正在使用內容可編輯div。

source that i looked at

回答

9

試試這個

function doGetCaretPosition (oField) { 

// Initialize 
var iCaretPos = 0; 

// IE Support 
if (document.selection) { 

    // Set focus on the element 
    oField.focus(); 

    // To get cursor position, get empty selection range 
    var oSel = document.selection.createRange(); 

    // Move selection start to 0 position 
    oSel.moveStart ('character', -oField.value.length); 

    // The caret position is selection length 
    iCaretPos = oSel.text.length; 
} 

// Firefox support 
else if (oField.selectionStart || oField.selectionStart == '0') 
    iCaretPos = oField.selectionStart; 

// Return results 
return (iCaretPos); 
} 
+0

THKS ** **歡呼不錯 – officegunner 2012-02-21 23:06:20

+0

工作雅! +1 – 2012-09-27 20:04:50

+0

它已在Internet Explorer 10+上測試過? – 2013-11-26 17:24:55