【发布时间】:2016-01-09 18:57:25
【问题描述】:
我正在尝试从 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。
【问题讨论】:
标签: javascript select word