如何获得没有焦点的输入的选定文本/插入位置? [英] How to get selected text/caret position of an input that doesn't have focus?
问题描述
如果该字段不具有焦点,可以(可靠地)在输入文本框中获取选定的文本/插入符号位置?
如果没有,获取和保存这些数据的最好方法是什么?基本上,当用户点击一个按钮时,我想在插入位置插入一些文本。但是,只要用户点击该按钮,该字段就会失去焦点,我将失去插入位置。 解决方案
以下脚本将保存插入位置,然后点击按钮将文本插入存储的位置:
Javascript:
< script type =text / javascript>
//获取游标的位置
函数getCaret(el){
if(el.selectionStart){
return el.selectionStart;
} else if(document.selection){
el.focus();
var r = document.selection.createRange();
if(r == null){
return 0;
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart',re);
return rc.text.length;
}
return 0;
函数InsertText(){
var textarea = document.getElementById('txtArea');
var currentPos = getCaret(textarea);
var strLeft = textarea.value.substring(0,currentPos);
var strMiddle = - Hello World - ;
var strRight = textarea.value.substring(currentPos,textarea.value.length);
textarea.value = strLeft + strMiddle + strRight;
}
< / script>
HTML:
< textarea id =txtArea> Lorem ipsum dolor sit amet,consectetur adipiscing elit。< / textarea>
< button onclick =InsertText();>插入文字< / button>
如果要将插入符号放在变量onblur中,可以修改脚本。
Is it possible to (reliably) get the selected text/caret position in a input text box if that field doesn't have focus?
If not, what's the best way to get and retain this data?
Basically, when a user clicks a button I want to insert some text at the caret position. However, as soon as the user clicks that button, the field loses focus and I lose the caret position.
The following script will hold the caret position and then a button click will insert text at the stored position:
Javascript:
<script type="text/javascript">
//Gets the position of the cursor
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
function InsertText() {
var textarea = document.getElementById('txtArea');
var currentPos = getCaret(textarea);
var strLeft = textarea.value.substring(0,currentPos);
var strMiddle = "-- Hello World --";
var strRight = textarea.value.substring(currentPos,textarea.value.length);
textarea.value = strLeft + strMiddle + strRight;
}
</script>
HTML:
<textarea id="txtArea" >Lorem ipsum dolor sit amet, consectetur adipiscing elit.</textarea>
<button onclick="InsertText();">Insert Text</button>
The script can be modified if you want to hold the caret position in a variable onblur.
这篇关于如何获得没有焦点的输入的选定文本/插入位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!