如何在Javascript中找到选择文本的开始和结束位置? [英] How to find the selection text beginning and end positions in Javascript?
问题描述
我试图找到选择的文本开始和结束。所以,在下面的文章中,如果我从你好,世界!这是多么美好的一天!中选择世界!真好!,我应该得到7作为起始坐标,并且24作为假设的终点坐标基于零的索引。
这是如何实现的?
编辑:
我正在寻找选择不在< input>
或< textarea>
元素内的文本。
编辑:
决定使用禁用的解决方案< textarea> s
/ *返回3个字符串,选择之前的部分,选择之后的部分和选定的部分* /
函数getSelected()
{
var u = editor.val();
var start = editor.get(0).selectionStart;
var end = editor.get(0).selectionEnd;
return [u.substring(0,start),u.substring(end),u.substring(start,end)];
}
其中编辑器是 $(#editor)
$ b <$ p $ (选择[0] +'< h1>'+选择[2] +'< / h1>'+选择[ 1]);
会在H1中换行选定的文字。如果没有选择,它只会添加空H1,但您可以添加支票和功能,以您喜欢的方式。
**没有在所有浏览器中测试过, *
I am trying to find the textual start and end of the selection. So, in the following text, if I selected "world! What a fine" from within "Hello, world! What a fine day it is!", I should get 7 as the start coordinate, and 24 as the end coordinate assuming a zero based index.
How is this achievable?
EDIT:
I am looking to find the selection of text that is not inside any <input>
or <textarea>
elements.
EDIT:
Decided the solution to use disabled <textarea>s
I use this:
/* Returns 3 strings, the part before the selection, the part after the selection and the selected part */
function getSelected()
{
var u = editor.val();
var start = editor.get(0).selectionStart;
var end = editor.get(0).selectionEnd;
return [u.substring(0, start), u.substring(end), u.substring(start, end)];
}
where editor is $("#editor")
or whatever ID your textarea / input field may have.
Usage:
var select = getSelected()
editor.val(select[0] + '<h1>'+ select[2] + '</h1>' + select[1]);
Will wrap selected text in H1. If nothing is selected it will just add empty H1, but you can add checks and functionality to your liking.
** Not tested in all browsers, works in Chrome though **
这篇关于如何在Javascript中找到选择文本的开始和结束位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!