获取用户选择的文本相对简单 . 涉及jQuery没有任何好处,因为除了 window 和 document 对象之外什么都不需要 .
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
如果您对一个也将处理 和texty 元素中的选择的实现感兴趣,您可以使用以下内容 . 因为它忽略了IE <= 8支持所需的代码,但是我已经在很多地方发布了SO的东西 .
function getSelectionText() {
var text = "";
var activeEl = document.activeElement;
var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
if (
(activeElTagName == "textarea") || (activeElTagName == "input" &&
/^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
(typeof activeEl.selectionStart == "number")
) {
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
} else if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
document.onmouseup = document.onkeyup = document.onselectionchange = function() {
document.getElementById("sel").value = getSelectionText();
};
Selection:
Please select some text.
Some text in a textarea