JavaScript 网页端复制图片到剪切板
2018-02-07 21:37
5027 人阅读
分类:
前端页面可能需要复制图片到剪切板的功能,这里使用JavaScript来实现这一功能,兼容大部分浏览器
全部代码
<html> <head> <title>复制图片到剪切板</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="jquery-1.10.2.js"></script> </head> <body> <div id="imgDyaminQrcodeContent"> <div class="zf-mass-code-img"> <img id="imgDyaminQrcode" src="images/1.jpg" alt="" > </div> <a id="linkCopyImage" href="#">复制图片</a> </div> </body> <script type="text/javascript"> var SelectText = function (element) { var doc = document; if (doc.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); } } //复制图片 var copyImage = document.getElementById("linkCopyImage"); copyImage.onclick = function(e){ //Make the container Div contenteditable $(".zf-mass-code-img").attr("contenteditable", true); //Select the image SelectText($('.zf-mass-code-img').get(0)); //Execute copy Command //Note: This will ONLY work directly inside a click listenner document.execCommand('copy'); //Unselect the content window.getSelection().removeAllRanges(); //Make the container Div uneditable again $('.zf-mass-code-img').removeAttr("contenteditable"); //Success!! alert('复制图片成功'); } </script> </html>
ps: 需要部署到服务器才能预览复制图片效果
和博主交个朋友吧