如何使用JavaScript获取所选文本?

时间:2014-11-25 17:18:57

标签: javascript jquery

我有一个包含一些歌词的DIV字段。我想知道用户何时被拖动&选择了部分歌词。怎么做到这一点?示例如下所示:

image

在此示例中,用户被拖动&选择了具有蓝色背景的部分。我希望JavaScript选择"我无法相信我的理智在于放弃你"部分文字。这可能吗?

3 个答案:

答案 0 :(得分:4)

我认为这个是你想要的:



if (!window.x) {
  x = {};
}

x.Selector = {};
x.Selector.getSelected = function() {
  var t = '';
  if (window.getSelection) {
    t = window.getSelection();
  } else if (document.getSelection) {
    t = document.getSelection();
  } else if (document.selection) {
    t = document.selection.createRange().text;
  }
  return t;
}

$('#html1').ready(function() {
  $(document).bind("mouseup", function() {
    var mytext = x.Selector.getSelected();
    alert(mytext);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="html1">They kill me for waiting you. I can't recall a more bla bla bla bla

</div>
&#13;
&#13;
&#13;

http://jsfiddle.net/0mqo0zhk/

答案 1 :(得分:2)

参考:How to get selected text with JavaScript

这已经回答了,它对我也有用。我已经分享了答案以及链接。希望它也能帮到你。

function GetSelectedText () {
if (window.getSelection) {  // all browsers, except IE before version 9
    var range = window.getSelection ();
    alert (range.toString ());
} 
else {
    if (document.selection.createRange) { // Internet Explorer
        var range = document.selection.createRange ();
        alert (range.text);
    }
}
}

var butn = document.getElementById("soda");
butn.onclick = function(){
    GetSelectedText();
}

答案 2 :(得分:0)

window.getSelection().toString()