最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to find the selection text beginning and end positions in Javascript? - Stack Overflow

programmeradmin1浏览0评论

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 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

Share Improve this question edited Dec 19, 2011 at 5:12 Tyler asked Dec 17, 2011 at 5:10 TylerTyler 19.9k21 gold badges102 silver badges158 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

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 **

This is possible but slightly plicated with contenteditable HTML content (as opposed to text within an <input> or <textarea> element). Here's a simple cross-browser implementation:

https://stackoverflow./a/4812022/96100

But I know a jQuery plugin that aims your problem and much more - https://github./localhost/jquery-fieldselection

发布评论

评论列表(0)

  1. 暂无评论