[英]document.getSelection().toString() returns empty string when the text is selected via element.select()
I am trying to implement the following two features: 我正在尝试实现以下两个功能:
textarea
by clicking a button. textarea
复制内容。 copy
event. copy
事件,我可以知道用户复制了哪些内容(用户是否使用按钮,Ctrl-C或上下文菜单进行copy
。 Here is my code (you can also see it in https://jsfiddle.net/hjtswedm/3/ ): 这是我的代码(您也可以在https://jsfiddle.net/hjtswedm/3/中看到它):
<html>
<head>
</head>
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<script>
$(window).bind("copy", function (e) {
alert(document.getSelection().toString());
});
var copyText = function () {
var txt = document.createElement("textarea");
txt.textContent = $('#data').val();
txt.style.position = "fixed";
document.body.appendChild(txt);
txt.select();
try {
return document.execCommand("copy");
} catch (ex) {
return false;
} finally {
document.body.removeChild(txt);
}
}
</script>
<body>
Lorem Ipsum
<textarea id="data">test copy</textarea>
<button onclick="copyText()">
Copy Text
</button>
</body>
</html>
This code works fine with Chrome. 这段代码可以在Chrome上正常运行。 However, with Firefox, Internet Explorer, and Edge, when I click the copy button,
document.getSelection().toString()
always returns empty strings. 但是,对于Firefox,Internet Explorer和Edge,当我单击复制按钮时,
document.getSelection().toString()
始终返回空字符串。 Is this by design, or did I miss something? 这是设计使然,还是我想念什么?
Thanks in advance. 提前致谢。
Try : 尝试:
try {
var range = document.createRange();
range.selectNodeContents(txt);
window.getSelection().addRange(range);
return document.execCommand("copy");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.