我有图像列表。我想将点击的数据属性复制到剪贴板。我现在拥有的是alert data-attribute。我试过复制命令,但它没有工作(不要复制任何东西)。拜托,有人可以帮我吗?
var emojiImages = document.getElementsByClassName('emoji-image');
for(var i=0; i< emojiImages.length; i++){
emojiImages[i].onclick = function(){
var a = this.getAttribute('data-emoji');
alert(a);
}
}
&#13;
<ul style="display: block; column-count: 8;"><li>:first:<img class="emoji-image" src="https://www.gravatar.com/avatar/086495a58faa8219a2640ad87325a12d?s=48&d=identicon&r=PG&f=1" width="36" height="36" data-emoji=":first:"></li><li>:second:<img class="emoji-image" src="https://www.gravatar.com/avatar/086495a58faa8219a2640ad87325a12d?s=48&d=identicon&r=PG&f=1" width="36" height="36" data-emoji=":second:"></li></ul>
&#13;
答案 0 :(得分:2)
如果屏幕上有可见的textarea或输入元素,复制命令的效果很好。
所以在其中创建一个put文本,复制textarea内容,然后将其删除。
var emojiImages = document.getElementsByClassName('emoji-image');
for(var i=0; i< emojiImages.length; i++){
emojiImages[i].onclick = function(){
var a = this.getAttribute('data-emoji');
var textArea = document.createElement("textarea");
textArea.value = a;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
}
&#13;
<ul style="display: block; column-count: 8;"><li>:first:<img class="emoji-image" src="https://www.gravatar.com/avatar/086495a58faa8219a2640ad87325a12d?s=48&d=identicon&r=PG&f=1" width="36" height="36" data-emoji=":first:"></li><li>:second:<img class="emoji-image" src="https://www.gravatar.com/avatar/086495a58faa8219a2640ad87325a12d?s=48&d=identicon&r=PG&f=1" width="36" height="36" data-emoji=":second:"></li></ul>
&#13;
检查已接受的答案here,更详细地解释了复制操作。