前端页面可能需要复制图片到剪切板的功能,这里使用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('复制图片成功');
}
ps: 需要部署到服务器才能预览复制图片效果