Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

selection - Get selected text on the page (not in a textarea) with jQuery

This plugin lets you grab text the user has selected in a textarea, and this site has non-jQuery-based instructions for grabbing text the user has selected outside of a text area.

I'm wondering whether the functionality of the latter is available in any jQuery plugin.

Edit: Also, is it possible to get the starting and ending indexes of the selection? I.e., where the selection starts and ends within the containing element?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason it's hard to find a plug-in for this isn't that it isn't very "jQuery"ish. By that I mean that jQuery plugins normally operate on jQuery objects and the selection has nothing to do with any elements.

Edit: I missed the fact you posted this link in your question but I'll leave it below for completeness since my version is formatted better (but otherwise identical). :)

<script language=javascript>
function getSelText() {
  var txt = '';
  if (window.getSelection) {
    txt = window.getSelection();
  } else if (document.getSelection) {
    txt = document.getSelection();
  } else if (document.selection) {
    txt = document.selection.createRange().text;
  } else return;
  document.aform.selectedtext.value =  txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()"> 
<form name=aform >
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...