我正在尝试使用以下代码在单击时选择元素的文本:
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
虽然文本被突出显示,但使用 Ctrl + C 时,空字符串会被复制到剪贴板。检查 selection.toString() 也会返回一个空字符串。知道为什么会发生这种情况吗?
最佳答案
嗯,我看了看你的代码并尝试了:
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');
})
关于javascript - 尽管选择了范围,selection.toString() 仍返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42167692/