在网站建设过程中做Web前端时,遇到需求通过js实现文本复制的功能。经过一番测试,终于实现了出来,有需要的小伙伴可以参考下,兼容多浏览器,兼容IE和火狐浏览器:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript 复制功能代码,兼容多浏览器</title>
</head>
<script language="javascript">
copyValue=function(strValue){
if(isIE()){
clipboardData.setData("Text",strValue);
alert("您已成功复制了此地址");
}else{
copy(strValue);
alert("内容已被复制!");
}
}
function isIE(number){
if(typeof(number)!=number){
return!!document.all;
}
}
function copy(text2copy){
var flashcopier = 'flashcopier';
if(!document.getElementById(flashcopier)){
var divholder = document.createElement('div');
divholder.id = flashcopier;
document.body.appendChild(divholder);
}
document.getElementById(flashcopier).innerHTML = '';
var divinfo = '<img src="http://www.webmy.cn/images/logo.jpg" alt="绵阳动力网络公司">';//这里是关键 document.getElementById(flashcopier).innerHTML = divinfo; } </script>
<div class="phoinfo"> 贴图地址:<input name="txtPhotoPath" value="www.webmy.cn" id="txtPhotoPath" type="text" size="65" />
<input type="button" name="btnCopy" id="btnCopy" onClick="copyValue('www.webmy.cn);" value="复制" /> </div>
</body>
</html>