Get selected text outside textbox with jquery
Is it possible to retrive selected text outside textbox? I had seen solutions to get text from input forms and textarea开发者_如何学运维s, similar to this: http://laboratorium.0xab.cd/jquery/fieldselection/0.2.3-test/test.html but can this aplied on HTML text (inside div element)?
For example, I want user to be able to bold selected text which is not in textarea.
Yes, it's possible. IE and other browsers have rather different mechanisms for dealing with selections. If you simply want the selected text, the following will do it:
function getSelectedText() {
var text = "";
if (window.getSelection) {
text = "" + window.getSelection();
} else if (document.selection && document.selection.createRange &&
document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
To address your specific question, you can use document.execCommand("bold", null, false);
to make the current selection bold. In non-IE browsers you have to temporarily put the document into edit mode first though:
function toggleSelectionBold() {
var range, sel;
if (window.getSelection) {
// Non-IE case
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand("bold", null, false);
document.designMode = "off";
} else if (document.selection && document.selection.createRange &&
document.selection.type != "None") {
// IE case
range = document.selection.createRange();
range.execCommand("bold", null, false);
}
}
In order to get the selected text in any part of the document you can use window.getSelection
, document.getSelection
or document.selection
. You should try each of the above if you want to achieve cross-compatibility, like:
if (window.getSelection) {
window.getSelection();
} else if (document.getSelection) {
document.getSelection();
} else if (document.selection) {
document.selection.createRange().text;
}
精彩评论