尽管选择了范围,selection.toString()仍返回空字符串

时间:2017-02-10 19:57:33

标签: javascript range selection

我正在尝试使用以下代码选择元素的文本:

.tickValues(data.map(d=>d.date))

虽然文本突出显示,但使用Ctrl + C将空字符串复制到剪贴板。检查selection.toString()也返回空字符串。知道为什么会这样吗?

1 个答案:

答案 0 :(得分:2)

嗯,我看了你的代码并尝试了:

var selection = window.getSelection();
var selectionText = selection.anchorNode.textContent

我得到了所选的文字内容。

编辑:看起来它被包裹在点击功能中......一秒钟。

$('<your selector goes here>').click(function(e) {
  var selection = window.getSelection();
  var range = document.createRange();
  range.selectNodeContents(e.target);
  selection.removeAllRanges();
  selection.addRange(range);
  console.dir(selection.anchorNode.textContent);
  //text content should display...
  //now that the content is highlighted, you can copy it
  document.execCommand('copy');

})