gpt4 book ai didi

javascript - 自动复制 html 表格内的文本

转载 作者:行者123 更新时间:2023-12-03 08:24:42 27 4
gpt4 key购买 nike

希望大家一切都好。我用一些 CSS 创建了一个 HTML。它的作用是在悬停时突出显示表格,并在单击时突出显示表格内的整个文本行。我想要实现的下一件事是自动复制突出显示的文本或单击时自动复制。我尝试了一些谷歌浏览器自动复制扩展,但是它不起作用。就像它不适用于 Google 电子表格单元格一样。

我一直在考虑 JavaScript,但我不太确定是否可以自动复制 HTML 表格中突出显示的文本。

对此有什么建议或技巧吗?

    <script>
if (!('select' in HTMLTableCellElement)) {
HTMLTableCellElement.prototype.select = function() {
var range = document.createRange();
range.selectNodeContents(this);
window.getSelection().addRange(range);
}
}
</script>

<style type="text/css">

table{
table-layout: fixed;
width: 170px;
height: 35px;
font-size: 14px;color:#333333;width:100%;border-width: 1px;border-color: #9dcc7a;border-collapse: collapse;
}

table td {
font-size: 12px;border-width: 1px;padding: 10px;border-style: solid;border-color: #9dcc7a;
overflow: hidden;
text-overflow: ellipsis;
width: 225px;
white-space: nowrap;
}

table th {
font-size:12px;color: black; background-color:#ffff99; border-width: 1px;padding: 8px;border-style: solid;border-color: #9dcc7a;
text-align: center;
width: 230px;
}

#table tr {background-color:#ffffff;}
#table tr:hover {background-color:#ffff99;}

::selection {
background-color: orange;
color: blue;
}



#tableheader
th {
font-size:12px;background-color:#abd28e;border-width: 1px;padding: 8px;border-style: solid;border-color: #9dcc7a;
text-align: left;
width: 230px;

</style>

</head>
<body>

<table class="table" border="1">
<tr><th>Header</th></tr>
<tr><td onclick="this.select()">This will be highlighted on click. It should also be copied to clipboard automatically</td></tr>
</table>

我期待您的回复。

最好,

杰森

最佳答案

您确实可以使用 JavaScript(尤其是某些库)来实现将某些文本(可能从当前页面的某个位置)直接复制到用户的剪贴板中。

请引用post它使用 clipboard.js图书馆。

这个想法是向应该可点击的元素添加一个特定的类(例如 btn),并且点击时必须将哪些内容复制到剪贴板。

<td class="btn">This will be ...</td>

然后添加以下 Clipboard API 的功能:

var clipboard = new Clipboard('.btn', {
// The selection of the correct content is done here.
text: function(trigger) {
return trigger.innerHTML;
}
//clipboard.js will take the entire inner content of the clicked element.
});

您的案例演示:http://jsfiddle.net/kv9ymLjn/

您还可以重新实现内容突出显示(剪贴板不需要它,但它可以向用户提供视觉反馈)。请参阅演示代码。

如问题评论中链接的帖子所示,最安全的方法是让用户执行实际的复制操作(例如 Ctrl + C),同时通过自动突出显示所需文本来帮助他/她。

另一方面,剪贴板库可能无法在所有环境中工作,即使涵盖了最常见的环境。

关于javascript - 自动复制 html 表格内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602314/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com