Home >Web Front-end >JS Tutorial >The implementation code for inserting a string at the cursor is compatible with IE and Firefox_javascript skills

The implementation code for inserting a string at the cursor is compatible with IE and Firefox_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:31:321058browse
Copy code The code is as follows:

// Insert string at the cursor
// myField text Box object
//The value to be inserted
function insertAtCursor(myField, myValue)
{
//IE support
if (document.selection)
{
myField. focus();
sel = document.selection.createRange();
sel.text = myValue;
sel.select();
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0')
{
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
// save scrollTop before insert
var restoreTop = myField.scrollTop;
myField.value = myField.value.substring(0, startPos) myValue myField.value.substring(endPos,myField.value.length);
if (restoreTop > 0)
{
// restore previous scrollTop
myField.scrollTop = restoreTop;
}
myField.focus();
myField.selectionStart = startPos myValue.length;
myField.selectionEnd = startPos myValue.length;
} else {
myField.value = myValue;
myField.focus();
}
}

The following is the Script House demo code:

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<script> // 在光标处插入字符串 // myField 文本框对象 // 要插入的值 function insertAtCursor(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; sel.select(); } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; // save scrollTop before insert var restoreTop = myField.scrollTop; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos,myField.value.length); if (restoreTop > 0) { // restore previous scrollTop myField.scrollTop = restoreTop; } myField.focus(); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; } else { myField.value += myValue; myField.focus(); } } </script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn