【问题标题】:JavaScript - select word from textJavaScript - 从文本中选择单词
【发布时间】: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


    【解决方案1】:

    您忘记将.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>

    【讨论】:

      【解决方案2】:

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

      console.log(txt.toString());
      

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

      【讨论】:

        猜你喜欢
        • 2019-04-18
        • 1970-01-01
        • 2012-08-15
        • 1970-01-01
        • 2017-06-25
        • 1970-01-01
        • 2013-02-02
        • 2010-09-07
        • 2014-05-24
        相关资源
        最近更新 更多