在javascript中将数据突出显示为popup

时间:2015-07-31 11:38:20

标签: javascript

如何从textarea获取鼠标悬停文本并使用javascript在弹出窗口中显示内容。在此用户可以自由选择并悬停任何文本,但文本必须只是一个字符串,并且可以&#39 ; t是textarea中存在的数字或特殊符号等。 代码如下

                                        输入文字:
                                                                                 
                                <br>
                                output:
                                    <span id="out"></span>
                                </div>
                                <script>
                                    function ShowSelectionInsideTextarea()
                                    {
                                        var textComponent = document.getElementById('Words');
                                        var selectedText;
                                        // IE version

                                        if (document.selection != undefined)
                                        {

                                            textComponent.focus();
                                            var sel = document.selection.createRange();
                                            selectedText = sel.text;


                                        }
                                        // Mozilla version
                                        else if (textComponent.selectionStart != undefined)
                                        {
                                            var startPos = textComponent.selectionStart;
                                            var endPos = textComponent.selectionEnd;
                                            selectedText = textComponent.value.substring(startPos, endPos)
                                            window.alert("hello");
                                        }


                                        document.getElementById("out").innerHTML = selectedText;

                                    }

                                    setInterval(ShowSelectionInsideTextarea, 1000);
                                </script>

这里的问题是警报没有得到鼠标悬停的文本而没有显示。在这种情况下该怎么办

1 个答案:

答案 0 :(得分:0)

灵感来自:How to get selected text from textbox control with javascript

你走了:

function getSelectionInsideTextarea(textComponent)
{
  var selectedText;

  if (document.selection != undefined)
  {
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }
  else if (textComponent.selectionStart != undefined)
  {
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos)
  }

  return selectedText;
}

var textArea = document.getElementById('mytextarea');
textArea.onselect = function(){ alert(getSelectionInsideTextarea(textArea)); };

工作示例:

https://jsfiddle.net/jve4eehh/6/