Try This JS Fiddle
這應該去做任何事情,但IE邊緣(我相信)
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;
}
document.body.addEventListener('mouseup', function() {
(window.getSelection()) ? addText(window.getSelection().toString(), window.getSelection().baseNode.parentNode) : addText(document.selection.toString(), document.selection.baseNode.parentNode);
});
function addText(text, parent) {
parent.appendChild(document.createTextNode(text));
}
,這個作品是它使用mouseUp事件,以確定是否文本可能已選擇的方式。所選文本存儲在window.getSelected()或document.selected()之下 - 然後將該值以及所選文本的父項傳遞給addText函數。它使用文檔appendChild和createTextNode方法將捕獲的文本追加到DOM。
在以前的IE版本中,他們使用document.select(),但是在Edge中,他們切換到getSelection(與其他人一樣),但是他們沒有實現與獲取文本時返回的值相同的值,真的抓住父節點並輕鬆追加到該節點。
因此,簡而言之,這會給你你在找什麼,但它不是跨瀏覽器和似乎沒有成爲一個辦法做到這一點很容易。
*「用戶選擇的文本」*是什麼意思? – adeneo
如您所看到的那樣,當您單擊並拖動文本並將其突出顯示時 –
沒有這個事件 – adeneo