2012-04-13 92 views
2

我在我的web應用程序中使用dhtml(midas)編輯器作爲html編輯器,我想要做的是在此html編輯器中獲得聚焦的光標,按照鼠標,是否有辦法去做?Javascript html編輯器光標焦點跟隨鼠標

追加例題: 我想光標在textarea的跟隨鼠標,所以如果你在你的文字區域有一個大的文字,你會在它與鼠標,光標(文本光標)應遵循鼠標,就像這樣:

「這是一個非常簡單的文本」 - 如果鼠標在「example」單詞之上,並且在x和a之間,那麼文本光標(|)應該集中在那裏,但是當我移動鼠標時,例如「text」應該位於鼠標當前所在的字母之間。

+0

什麼是你的HTML編輯器的ID /名稱? – Coder 2012-04-13 09:22:18

+0

ExtJS htmleditor組件。 – dfilkovi 2012-04-15 12:09:08

回答

2

好吧,我發現使用Ext.util.TextMetrics的解決方案,首先我得在編輯器中每個字符的位置,然後我比較,爲鼠標光標位置,然後根據從charNum陣列定的字符

htmlEditor.getEl().on('mousemove', function(e) 
{ 
    var charNum = {}, 
     text = htmlEditor.getValue(), 
     fWidth = htmlEditor.getWidth(); 

    var textMetrics = new Ext.util.TextMetrics(htmlEditor.getEl(), htmlEditor.getWidth()); 

    for(var n=0;n<text.length;n++) 
    { 
     var dat = text.substring(0, n) 
     var width = textMetrics.getWidth(dat); 
     var height = textMetrics.getHeight(dat); 

     if(width > fWidth) 
     { 
      var mult = Math.ceil(width/fWidth) 
      var width = width % fWidth; 
      height = height*mult; 
     } 

     charNum[n] = [width, height]; 
    } 

    //console.log("charNum: "+charNum.toSource()); 

    var mX = e.getX(); 
    var mY = e.getY(); 

    var cXY = htmlEditor.getEl().getXY(); 
    var cX = cXY[0]; 
    var cY = cXY[1];      

    var x = mX-cX-20; 
    var y = mY-cY; 

    //console.log("fin xy: "+x+' '+y); 

    var n = -1; 
    var z = 0; 
    for(key in charNum) 
    { 
     if(charNum[key][0] > x && charNum[key][1] > y) 
     { 
      n = key-1; 
      break; 
     } 
     n++; 
     z++; 
    } 

    if(x < 0 && y < 14) n = -1; 


    if(n == (z-1) && n != -1) 
    { 
     n++; 
    } 

    var selection = htmlEditor.win.getSelection(); 

    range = selection.getRangeAt(0); 
    range.selectNodeContents(htmlEditor.getEditorBody()); 
    range.collapse(true); 
    for(var x=0;x<n;x++) 
    { 
     selection.modify("move", "forward", "character"); 
    } 
}); 
0

我還沒有試過@dfilkovi的解決方案更新MIDAS選擇,但儘管它可以是正確的,記住,任何解決方案結合了事件鼠標移動會大多數是c這在cpu上造成了巨大的開銷。

爲了緩解這種症狀,您可以在處理程序中首先解除偵聽器的綁定,然後設置超時以在幾毫秒後綁定它;是這樣的:

// assume HandleOriginal as the original function declared by @dfilkovi 

// attach the listener 
startListener(); 

// functions 
function startListener() { 
    htmlEditor.getEl().on('mousemove', HandleAndWait); 
} 

function stopListener() { 
    // maybe this is not the right syntax 
    htmlEditor.getEl().on('mousemove', null); 
} 

function HandleAndWait(e) { 
    var C_SLEEP = 50; 
    stopListener(); 

    try { HandleOriginal(e); } 
    finally { window.setTimeout(startListener, C_SLEEP); } 

} 

可以的話,微調的C_SLEEP到最佳的用戶體驗的價值。