87,910
社区成员
发帖
与我相关
我的任务
分享
document.getElementsByClassName("icon-copy")[0].addEventListener("click", function() {
console.log('点击');
var id = document.getElementById('copy-input-div');
if(id){
document.body.removeChild(id);
}
var myInput = document.createElement("input");
var inputDiv = document.createElement("div");
inputDiv.id='copy-input-div';
myInput.id = 'copyId';
myInput.value = url;
document.body.appendChild(inputDiv);
inputDiv.appendChild(myInput);
var obj = document.getElementById('copyId');
obj.select();
try {
if(document.execCommand('Copy')){
document.execCommand('Copy');
console.log('copy success');
alert('复制成功');
} else {
console.log('false');
}
} catch (err){
console.log('报错:');
console.log(err);
}
});
现在火狐好用了,url我要拷贝的值,但是现在不知道为啥360极速模式execCommand('Copy')返回的是false,兼容模式好用,是因为我360的webKit内核版本低吗,还是因为别的原因
我看网上说返回false是因为execCommand('Copy')不被支持或未被启用,这个怎么判断或解决
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=6,chrome=1" />
<title> 页面名称 </title>
</head>
<body>
<p>点击复制后在右边textarea CTRL+V看一下</p>
<input type="button" id="btn" value="复制"/>
<textarea rows="4"></textarea>
<script type="text/javascript">
function copyText(text) {
var textarea = document.createElement("textarea");
var currentFocus = document.activeElement;
document.body.appendChild(textarea);
textarea.value = text;
textarea.focus();
if (textarea.setSelectionRange)
textarea.setSelectionRange(0, textarea.value.length);
else
textarea.select();
try {
var flag = document.execCommand("copy");
} catch(eo){
var flag = false;
}
document.body.removeChild(textarea);
currentFocus.focus();
return flag;
}
document.getElementById('btn').onclick = function(){
var flag = copyText("abcdef");
alert(flag ? "复制成功!" : "复制失败!");
};
</script>
</body>
</html>
window.onload = function(){
document.onclick = function(){
var textarea = document.createElement('textarea');
textarea.value = location.href;
var div = document.createElement('div');
div.appendChild(textarea);
div.style.position = 'absolute';
div.style.left = '-10000px';
div.style.top = '-10000px';
document.getElementsByTagName('body')[0].appendChild(div);
textarea.select();
document.execCommand('Copy');
document.getElementsByTagName('body')[0].removeChild(div);
}
}
我只测试了IE7IE8IE9chrome,其他浏览器倒是没仔细测试过。。应该是差不多的。