是否可以在文本框之外检索选定的文本? 我见过从输入表单和文本区域获取文本的解决方案,类似于: http://laboratorium.0xab.cd/jquery/fieldselection/0.2.3-test/test.html 但这可以应用于 HTML 文本(div 元素内)吗?
例如,我希望用户能够将不在文本区域中的选定文本加粗。
最佳答案
是的,这是可能的。 IE 和其他浏览器有相当不同的处理选择的机制。如果您只想要选定的文本,则可以执行以下操作:
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;
}
要解决您的具体问题,您可以使用 document.execCommand("bold", null, false);
将当前选择设置为粗体。在非 IE 浏览器中,您必须先暂时将文档置于编辑模式:
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);
}
}
关于javascript - 使用jquery获取文本框外的选定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3701478/