Tôi tìm kiếm trên internet và không thể tìm thấy một giải pháp này vì vậy tôi đã đi trước và thử nghiệm. làm việc thành công trên tất cả các trình duyệt:
HTML Tôi đang sử dụng để thử nghiệm là:
<div class="copyable">
<img src="images/sherlock.jpg" alt="Copy Image to Clipboard via Javascript."/>
</div>
<div class="copyable">
<img src="images/stark.jpg" alt="Copy Image to Clipboard via Javascript."/>
</div>
JavaScript/jQuery Mã trông như thế này:
<script>
//Cross-browser function to select content
function SelectText(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);
}
}
$(".copyable").click(function (e) {
//Make the container Div contenteditable
$(this).attr("contenteditable", true);
//Select the image
SelectText($(this).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
$(this).removeAttr("contenteditable");
//Success!!
alert("image copied!");
});
</script>
đã tải lên trên GitHub cũng như: https://github.com/owaisafaq/copier-js
Không có hỗ trợ để sao chép dữ liệu hình ảnh vào clipboard trong chrome. https://bugs.chromium.org/p/chromium/issues/detail?id=150835. Có vẻ như nó đã được mở trong khoảng 4 năm nay. – notsiddhartha