简体   繁体   English

使用javascript代码将HTML元素复制到剪贴板

[英]Copy HTML elements to clipboard using javascript code

I am not trying to copy text to the clipboard. 不是想将文本复制到剪贴板。 I have an array of html elements (contiguous divs) representing cells in a grid. 我有一个html元素数组(连续的div)表示网格中的单元格。 They are selected using jquery and I am trying to find out if there is a way to copy them onto the clipboard like a table that can be pasted elsewhere, like in MS excel for example. 它们是使用jquery选择的,我试图找出是否有办法将它们复制到剪贴板上,就像可以粘贴到其他地方的表一样,例如在MS excel中。

Every resource on the internet only talks about copying text, not html elements. 互联网上的每个资源都只涉及复制文本,而不是html元素。

You can stringify a DOM element node or a tree using [selector].outerHTML . 您可以使用[selector].outerHTML对DOM元素节点或树进行字符串化。 The most direct approach would be to show a prompt that contains the HTML element text, which you can then copy off of: 最直接的方法是显示包含HTML元素文本的提示,然后您可以将其复制出来:

var selectedText = [selector].outerHTML;
function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", selectedText);
}
// Using http://stackoverflow.com/a/6055620/3157745

As for the export into Excel, there's no way you can simply copy and paste a string of any sorts and drop that into a table. 至于导出到Excel,你无法简单地复制和粘贴任何类型的字符串并将其放入表中。 However, what you can do is parse the HTML element, format that into a CSV, which then can be opened with Excel. 但是,您可以做的是解析HTML元素,将其格式化为CSV,然后可以使用Excel打开。 As for how that might be achieved, we'd need to see the structure of your HTML. 至于如何实现,我们需要看到HTML的结构。


Update 更新

If possible, try using jquery DataTables . 如果可能,请尝试使用jquery DataTables It can export your Table as XLSX, CSV, PDF and all you would need to do is initialize your table with: 它可以将您的表导出为XLSX,CSV,PDF,您需要做的就是使用以下内容初始化表:

$(document).ready(function() {
    $('#example').DataTable()
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM