如何在htmlText文本框光标处插入字符
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在htmlText文本框光标处插入字符相关的知识,希望对你有一定的参考价值。
参考技术A <!DOCTYPE html><html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<p>第一种:</p>
<textarea name="" id="" cols="30" rows="10">这是文本域</textarea>
<br><br>
<p>第二种:</p>
<form action="">
<input type="text" placeholder="这也是文本域"><br><br><br>
<input type="text" placeholder="这也是文本域">
</form>
</body>
</html>
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:
*
*/
// 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: <input type="text" id="myInput" /> <input type="submit" value="insert ® symbol" onClick="insertThisInThere('®', 'myInput');" /> * */ // my bp-ized version so people won't know I stole it all, but really just so I can understand it better function insertThisInThere(thisChar, thereId) { function theCursorPosition(ofThisInput) { // set a fallback cursor location var theCursorLocation = 0; // find the cursor location via IE method... if (document.selection) { ofThisInput.focus(); var theSelectionRange = document.selection.createRange(); theSelectionRange.moveStart('character', -ofThisInput.value.length); theCursorLocation = theSelectionRange.text.length; } else if (ofThisInput.selectionStart || ofThisInput.selectionStart == '0') { // or the FF way theCursorLocation = ofThisInput.selectionStart; } return theCursorLocation; } // now get ready to place our new character(s)... var theIdElement = document.getElementById(thereId); var currentPos = theCursorPosition(theIdElement); var origValue = theIdElement.value; var newValue = origValue.substr(0, currentPos) + thisChar + origValue.substr(currentPos); theIdElement.value = newValue; } /** EXAMPLE HTML: <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> <br/><hr /><br/> <input type="text" id="inputOne" value="inputOne" /><br /> <input type="submit" onClick="insertThisInThere('*A*','inputOne')" value="insert *A* into inputOne" /> <br/><hr /><br/> <textarea id="inputTwo">inputTwo</textarea><br /> <button onClick="insertThisInThere('*B*','inputTwo');">insert *B* into inputOne</button> **/
以上是关于如何在htmlText文本框光标处插入字符的主要内容,如果未能解决你的问题,请参考以下文章