Created
December 5, 2019 04:50
-
-
Save sailist/62ead288f6c941dcf4570e0d7e612d43 to your computer and use it in GitHub Desktop.
JavaScript在光标处插入文字
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// JS脚本区域 | |
function insertAtCursor(myField, myValue) { | |
//IE support | |
if (document.selection) { | |
document.selection.empty(); | |
caretPos.text = myValue; | |
caretPos.select(); | |
myField.focus(); | |
} | |
//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) { | |
myField.scrollTop = restoreTop; | |
} | |
myField.focus(); | |
myField.selectionStart = startPos + myValue.length; | |
myField.selectionEnd = startPos + myValue.length; | |
} else { | |
myField.value += myValue; | |
myField.focus(); | |
} | |
} | |
var caretPos ; | |
function setPos(){ | |
if (document.selection) { //IE | |
caretPos = document.selection.createRange(); | |
} | |
} | |
// HTML区域 | |
<textarea id="input" οnchange="setPos()" οnfοcus="setPos()"></textarea> | |
// 示例: | |
var ipt = document.getElementById("input"); | |
insertAtCursor(ipt,value["value"]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment