JavaScript - select 文本中的单词

JavaScript - select word from text

我正在尝试 select div 中文本中的一个词。我想单击一个文本,然后将鼠标指针下方的一个词放置到一个变量以供进一步处理。

function get_selection() {
 var txt = '';
 if (window.getSelection) {
     txt = window.getSelection();
 } else if (document.getSelection) {
     txt = document.getSelection();
 } else if (document.selection) {
     txt = document.selection.createRange().text;
 }
 console.log(txt);
}

document.getElementById("txt").onclick = get_selection;

我在控制台得到的是整段:

Selection { anchorNode: #text ""My text is long and wise and it consumes a lot of interwebs."", anchorOffset: 18, focusNode: #text ""My text is long and strong and it consumes a lot of interwebs."", focusOffset: 18, isCollapsed: true, rangeCount: 1, caretBidiLevel: 0 }

...与单击的词相反。

请指教。我不想使用 jQuery.

您忘记将 .toString 应用到 txt:

function get_selection() {
 var txt = '';
 if (window.getSelection) {
     txt = window.getSelection().toString();
 } else if (document.selection) {
     txt = document.selection.createRange().text;
 }
 document.getElementById("out").innerHTML = txt;
}

document.getElementById("txt").onclick = get_selection;
<div id="txt">"My text is long and wise and it consumes a lot of interwebs."</div>
<div id="out"></div>

您需要将 toString 添加到您的 getSelection 中:

console.log(txt.toString());

Jsfiddle:https://jsfiddle.net/h8u1a6ha/