使用jQuery获取页面上的选定文本(不在textarea中) [英] Get selected text on the page (not in a textarea) with jQuery

查看:94
本文介绍了使用jQuery获取页面上的选定文本(不在textarea中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此插件可让您抓取用户在文本区域中选择的文本,和此网站具有基于非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.

我想知道后者的功能是否在任何jQuery插件中都可用。

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

编辑:另外,是否可以获得选择的开始和结束索引?即,选择在包含元素中开始和结束的地方?

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?

推荐答案

很难为此找到插件的原因不是说它不是非常 jQuery的。我的意思是说jQuery插件通常可以在jQuery对象上运行,而选择与任何元素都没有关系。

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.

编辑:实际上,您在问题中发布了此链接,但出于完整性考虑,我将其保留在下面,因为我的版本格式更好(但其他方面相同)。 :)

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>

这篇关于使用jQuery获取页面上的选定文本(不在textarea中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆