javascript - 将多个项目的背景颜色复制到剪贴板
问题描述
我有几个li
不同背景颜色的标签。我想当用户单击每个li
标签时,获取该特定项目的背景颜色并将其复制到剪贴板。
$('li.col').click(function () {
var x = $(this).css('backgroundColor');
})
我怎样才能做到这一点?
解决方案
到目前为止,您的方法是正确的。您可以使用类似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 上写了一篇文章,更深入地解释了这项技术。你可以在这里阅读。
推荐阅读
- json - 如何使用不同的对象发出这个 POST 请求?
- node.js - 如何将相同的消息广播到 Mosca 中的多个接口
- python - scrapy-splash 活动内容选择器适用于 shell 但不适用于蜘蛛
- python - 当 Python 3 的 names=True 时,Numpy genfromtxt 似乎不起作用
- javascript - 基于另一个值打印一个值的对象
- wordpress - 产品图片未在 woocommerce 中显示
- regex - VIM 正则表达式捕获组什么也没捕获
- mongodb - 如何在 mongoDB 的嵌入式字段中获取总和
- python - 如何根据所有其他功能填充null
- javascript - 无法在网络服务器上加载内部 .js 文件