在Javascript中定位突出显示的文本

时间:2011-11-25 01:09:56

标签: javascript jquery html

寻找一种方法来定位所选文本并在Javascript中对其执行操作。我应该使用什么样的方法?这是jQuery的工作吗?非常感谢!

编辑:早期的答案都是针对CSS类的。我正在寻找点击和突出显示/选择文本,然后在JS中采取行动。谢谢!

编辑2:我被要求提供此功能的示例。 Here's一个,但代码的评论很差。让我知道你的想法。

2 个答案:

答案 0 :(得分:4)

Try window.getSelection,您还应该在SelectionRange上阅读。

答案 1 :(得分:4)

编写跨浏览器非常困难,通用"获取所选文本"功能。如果您可以限制您的要求仅说明在页面中选择的文本,那么生活就会更简单。

但是如果你想从任何地方(内部表格控件,按钮标签,一般文本)中选择文本,那么生活就很艰难。

这是我前一段时间写的一个函数,它对于它所用的应用程序运行良好:

/* 
 *  This function returns the selected text in a document.
 *  If no text selected, returns an empty string.
 *
 *  Call on one of the following events: 
 *
 *     mouseup - most appropriate event
 *               for selection by mousedown, drag to select, mouseup
 *               may select only whitespace
 *
 *    dblclick - not as appropriate as mouseup
 *               for selection of word by double click
 *               may select only whitespace
 *
 *  Note that text can be selected in ways that do not dispatch
 *  an event, e.g. selecting all the text in the document using:
 *     ctrl + a
 *     context menu -> Select All
 *     edit menu -> Select All
 *     programmatically selecting text
 */
function checkForSelectedText(e) {
  var e = e || window.event;
  var el = e.target || e.srcElement;
  var tagName = el.tagName && el.tagName.toLowerCase();
  var t;
  var d = document;

  // Try DOM 2 Range - for most browsers, including IE 6+
  // However, doesn't get text selected inside form controls
  // that allow selection of text content (input type text, 
  // textarea)
  if (d && d.selection && d.selection.createRange) {
    t = d.selection.createRange().text;

  // Otherwise try HTML5 - note that getSelection returns
  // a string with extra properties. This may also get
  // text within input and textarea
  } else if (d.getSelection) {
    t = d.getSelection();
  }

  // If didn't get any text, see if event was inside
  // inupt@type=text or textarea and look for text
  if (t == '') {
    if (tagName == 'textarea' || 
       (tagName == 'input' && el.type == 'text')) {

     // Check selectionStart/End as otherwise if no text
     // selected, IE returns entire text of element
     if (typeof el.selectionStart == 'number' && 
         el.selectionStart != el.selectionEnd) {
        t = el.value.substring(el.selectionStart, el.selectionEnd)
     }
    }
  }
  return t;
}