首页 > 解决方案 > 将多个项目的背景颜色复制到剪贴板

问题描述

我有几个li不同背景颜色的标签。我想当用户单击每个li标签时,获取该特定项目的背景颜色并将其复制到剪贴板。

 $('li.col').click(function () {
    var x = $(this).css('backgroundColor');
})

我怎样才能做到这一点?

标签: javascriptjquery

解决方案


到目前为止,您的方法是正确的。您可以使用类似30secondsofcodecopyToClipboard (我维护的项目/网站)中的方法来处理此问题。从网站:

创建一个新<textarea>元素,用提供的数据填充它并将其添加到 HTML 文档中。用于Selection.getRangeAt()存储选定的范围(如果有)。用于document.execCommand('copy')复制到剪贴板。从 HTML 文档中删除<textarea>元素。最后,用于Selection().addRange()恢复原始选定范围(如果有)。

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};


$('li.col').click(function() {
  var x = $(this).css('backgroundColor');
  copyToClipboard(x);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="col" style="background:red;">Red</li>
  <li class="col" style="background:green;">Green</li>
  <li class="col" style="background:blue;">Blue</li>
</ul>

注意:我在 Medium 上写了一篇文章,更深入地解释了这项技术。你可以在这里阅读。


推荐阅读