作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
此代码在 Google Chrome、Opera、IE 11 中运行良好。但在 Mozilla firefox 和 Safari 中不起作用。我在以下字符串中收到错误“var successful = document.execCommand('copy');”
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Test Copy</title>
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/bootstrap.js"></script>
<script src="js/npm.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<div id="text">
Copytextblalalalal
</div>
<button id="btnCopy" onclick="copyText()">COPY</button>
</div>
</div>
<script>
function copyText() {
var emailLink = document.querySelector('#text');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
window.getSelection().removeAllRanges();
}
</script>
</body>
</html>
最佳答案
从 Firefox 41(2015 年 9 月)开始,复制命令在从某些受信任的(用户触发的)事件触发时应该默认可用,例如响应按钮点击而触发的内容。 compatibility table来自 MDN 的更多信息,另请参阅 release notes .
问题中的代码因此应该有效。事实上,我测试了一些非常相似的东西(见下面的代码)并且它对我使用 Firefox 44 非常有用。
function doCopy() {
var textToCopy = document.getElementById('textToCopy');
var range = document.createRange();
range.selectNodeContents(textToCopy);
window.getSelection().addRange(range);
document.execCommand('copy');
}
(function() {
var el = document.getElementById("copyTrigger");
el.addEventListener("click", doCopy, false);
})();
textarea {display: block; margin-top: 1em; width: 500px;}
<div id="textToCopy">Elephant</div>
<button id="copyTrigger">Copy above text</button>
<textarea placeholder="Try pasting here to test"></textarea>
关于javascript - 如何在 Mozilla Firefox 中一键复制文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078763/
我是一名优秀的程序员,十分优秀!