2012-02-20 70 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