0

In a javascript function that I am developing, the user selects some content on a html web page. The content selected can include text, HTML elements, links and images.

Also, the content can start from some portion of one HTMl element, then entire content of some other HTML elements and so on.

I understand how to obtain the Ids of the html elements from which text has been selected.

However, how do I obtain only the portion of text within an HTML element that has been selected (viz. in case user has selected only some portion of content within an HTML Element- i.e. he has not selected the entire content of that element). Also, what is the easiest way to determine if the user has selected partial content or entire content within an HTML element? I would prefer a solution in JQuery but a javascript solution will also be fine with me.

4

1 回答 1

0

Try document.getSelection,它返回一个选择对象,该对象代表文档中选择的文本。它不会返回在 input 或 textarea 元素中选择的文本。或者尝试window.getSelection.

请参阅HTML5 DOM 范围

function getSelectedText() {

  // DOM
  // supported by Firefox, Chrome, Opera
  // Concatenate an empty string to fix bug in Safari <2.0 and Firefox < 1.0.3
  if (window.getSelection) {
    return window.getSelection() + '';

  // This seems to work in all browsers that support window.getSelection
  // and also IE 9+? (per MSDN, untested)
  } else if (document.getSelection) {
    return document.getSelection() + '';

  // IE 6, 7 & 8?
  } else if (document.selection) {
    return document.selection.createRange().text;

  } else {
    return null;
  }
}
于 2012-07-24T03:50:52.637 回答