Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 18:31:32
Original
1034 people have browsed it
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>
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template