2015-12-02 56 views
0

我有一些帶有文本的輸入字段(文本長度爲10個字符)。 我想獲取用戶點擊/點擊的光標位置。使用javascript獲取inputfield的mousedown上的光標位置

假設,如果用戶敲擊/點擊在2字符內的話,我想要得到的位置爲2

誰能幫助我在使用JavaScript/secnha/jQuery的實現這一目標?提前

感謝

+0

你到目前爲止還沒有嘗試過什麼?請參閱[如何提問](http://stackoverflow.com/help/how-to-ask/)和[如何創建最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve ) –

+0

另一個重複:http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field –

回答

0

檢查this fiddle看位置如何相對可以通過jQuery

this fiddle進行檢查,看看如何計算輸入文本的寬度

所以像(不是可執行代碼,只是算法)

$("input-field-selector").click(function(){ 

var positionXRelative = FromFirstFiddle(); 
var positionXRelative = positionXRelative - padding; 
var indexOfClick = positionXRelative/sizeOfCharacterFromSecondFiddle(); 

}); 
+0

感謝您的回覆@ gurvinder372 有三個div在firstFiddle。 哪種方法應該考慮獲得positionXRelative? 你可以請建議 – user3913867

+0

@ user3913867你可以嘗試第二和第三。 – gurvinder372

+0

再次感謝您的快速響應。 如何獲得'填充'? – user3913867