3

我有图像列表。我想在单击时将数据属性复制到剪贴板。我现在拥有的是警报数据属性。我尝试了复制命令,但它不起作用(不要复制任何东西)。拜托,有人可以帮我吗?

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);
    }
}
<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>

4

1 回答 1

5

如果屏幕上有文本区域或输入元素可见,则复制命令的想法非常有用。
因此,在其中创建一个放置文本,复制 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);
    }
    
}
<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>

在此处检查接受的答案,更详细地解释了复制操作。

于 2018-03-07T10:25:18.760 回答