JS-onclick函数将文本字符符号插入到光标处的文本输入字段或文本区域

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS-onclick函数将文本字符符号插入到光标处的文本输入字段或文本区域相关的知识,希望对你有一定的参考价值。

// big thanks to these tips for giving me code to steal: http://bit.ly/bundles/brandonjp/9

/*
* USAGE: give your html textarea or text input element an ID
* give your button an onClick="insertThisInThere(text2insert, theInputIDwhereItGoes);"
*
* EX:
*
*/
  1. // big thanks to these tips for giving me code to steal: http://bit.ly/bundles/brandonjp/9
  2.  
  3. /*
  4.  * USAGE: give your HTML textarea or text input element an ID
  5.  * give your button an onClick="insertThisInThere(text2insert, theInputIDwhereItGoes);"
  6.  *
  7.  * EX: <input type="text" id="myInput" /> <input type="submit" value="insert ® symbol" onClick="insertThisInThere('®', 'myInput');" />
  8.  *
  9.  */
  10.  
  11.  
  12. // my bp-ized version so people won't know I stole it all, but really just so I can understand it better
  13.  
  14. function insertThisInThere(thisChar, thereId) {
  15. function theCursorPosition(ofThisInput) {
  16. // set a fallback cursor location
  17. var theCursorLocation = 0;
  18.  
  19. // find the cursor location via IE method...
  20. if (document.selection) {
  21. ofThisInput.focus();
  22. var theSelectionRange = document.selection.createRange();
  23. theSelectionRange.moveStart('character', -ofThisInput.value.length);
  24. theCursorLocation = theSelectionRange.text.length;
  25. } else if (ofThisInput.selectionStart || ofThisInput.selectionStart == '0') {
  26. // or the FF way
  27. theCursorLocation = ofThisInput.selectionStart;
  28. }
  29. return theCursorLocation;
  30. }
  31.  
  32. // now get ready to place our new character(s)...
  33. var theIdElement = document.getElementById(thereId);
  34. var currentPos = theCursorPosition(theIdElement);
  35. var origValue = theIdElement.value;
  36. var newValue = origValue.substr(0, currentPos) + thisChar + origValue.substr(currentPos);
  37.  
  38. theIdElement.value = newValue;
  39.  
  40. }
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47. /** EXAMPLE HTML:
  48.  
  49. <h2>set your cursor anywhere inside the text field, then click the button to insert text at the cursor location -- each button has an onClick="sendChar2Id('®','toThisId');"</h2>
  50.  
  51. <br/><hr /><br/>
  52.  
  53. <input type="text" id="inputOne" value="inputOne" /><br />
  54. <input type="submit" onClick="insertThisInThere('*A*','inputOne')" value="insert *A* into inputOne" />
  55.  
  56. <br/><hr /><br/>
  57.  
  58.  
  59. <textarea id="inputTwo">inputTwo</textarea><br />
  60. <button onClick="insertThisInThere('*B*','inputTwo');">insert *B* into inputOne</button>
  61.  
  62. **/

以上是关于JS-onclick函数将文本字符符号插入到光标处的文本输入字段或文本区域的主要内容,如果未能解决你的问题,请参考以下文章

在光标处插入表情符号

Vim文本编辑器

在光标处插入反应

如何在htmlText文本框光标处插入字符

EditText在光标处插入字符

vim文本编辑器