簡體   English   中英

將整個 html 表復制到剪貼板 javascript

[英]copy whole html table to clipboard javascript

我已經將 javascript 寫入 select 表格,但我現在想在單擊按鈕后自動復制它。請幫助我。我的 javascript 是這樣的。

function selectElementContents(el) {
            var body = document.body, range, sel;
            if (document.createRange && window.getSelection) {
                range = document.createRange();
                sel = window.getSelection();
                sel.removeAllRanges();
                try {
                    range.selectNodeContents(el);
                    sel.addRange(range);
                    document.execCommand('Copy');
                } catch (e) {
                    range.selectNode(el);
                    sel.addRange(range);
                    document.execCommand('Copy');
                }
            } else if (body.createTextRange) {
                range = body.createTextRange();
                range.moveToElementText(el);
                range.select();
                range.execCommand('Copy');

            }
        }
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
    range = document.createRange();
    sel = window.getSelection();
    sel.removeAllRanges();
    try {
        range.selectNodeContents(el);
        sel.addRange(range);
    } catch (e) {
        range.selectNode(el);
        sel.addRange(range);
    }
} else if (body.createTextRange) {
    range = body.createTextRange();
    range.moveToElementText(el);
    range.select();
}
document.execCommand("Copy");}

嘗試這個:

<script type="text/javascript">

function copytable(el) {
    var urlField = document.getElementById(el)   
    var range = document.createRange()
    range.selectNode(urlField)
    window.getSelection().addRange(range) 
    document.execCommand('copy')
}

</script>

<input type=button value="Copy to Clipboard" onClick="copytable('stats')">

<table id=stats>
    <tr>
        <td>hello</td>
    </tr>
</table>
  • 這對我有用,它不僅限於表格,而且它甚至可以選擇並復制到剪貼板中使用 id 指定的 Node 內的所有元素。

  • 我已經在 Mac Chrome 和 windows chrome 中進行了測試。

  • 用例:復制簽名生成器基於JS創建的簽名

演示:

 <div id="signature_container"> <p id="company_name" style="margin-top: 4px; margin-bottom: 0px; color: #522e64; font-weight: 700; font-size: 16px; letter-spacing: 1px; border-bottom: solid 2px #522e64; width:250px; padding-bottom: 3px;">The Company Name</p> <p style="margin-top: 4px; margin-bottom: 0px; color: #00706a; font-weight: 700; font-size: 15px;"> <span id="first_name_output_2"></span>Firstname<span id="last_name_output_2"> Lastname</span>&nbsp;&nbsp;&nbsp;&nbsp;<span id="designation_output_2" style="color: #000000; font-weight: 500; font-size: 15px;">Designation</span></p> <p style="margin-top: 0px; margin-bottom: 0px; color: #625469; font-weight: normal; font-size: 15px; letter-spacing: 0.6px;">youreamil@xyz.com<span id="email_output_2"></span>&nbsp;&nbsp;&nbsp;</p> </div> <br><br> <input type="button" onclick="selectElementContents( document.getElementById('signature_container') );" value="Copy to Clipboard"> <script> function selectElementContents(el) { var body = document.body, range, sel; if (document.createRange && window.getSelection) { range = document.createRange(); sel = window.getSelection(); sel.removeAllRanges(); range.selectNodeContents(el); sel.addRange(range); } document.execCommand("Copy"); } </script>

更新

請改用此代碼。

代碼:

 function selectElementContents(el) { var body = document.body, range, sel; if (document.createRange && window.getSelection) { range = document.createRange(); sel = window.getSelection(); sel.removeAllRanges(); try { range.selectNodeContents(el); sel.addRange(range); } catch (e) { range.selectNode(el); sel.addRange(range); } } else if (body.createTextRange) { range = body.createTextRange(); range.moveToElementText(el); range.select(); document.execCommand("copy"); } }
 <input type="button" value="select table" onclick="selectElementContents( document.getElementById('table') );"> <table id="table"> <thead> <tr><th>Heading</th><th>Heading</th></tr> </thead> <tbody> <tr><td>cell</td><td>cell</td></tr> </tbody> </table>

通過使用名為clipboard.js的庫使其更容易。 有關更多信息,請查看: https : //webdesign.tutsplus.com/tutorials/copy-to-clipboard-made-easy-with-clipboardjs--cms-25086

<script src="//cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.4.0/clipboard.min.js">
(function(){
    new Clipboard('#copy-table-button');
})();
</script>

<button class="btn" id="copy-table-button" data-clipboard-target="#table_results">Copy</button>
               

<table id='table_results' >

</table>

以前的腳本對我不起作用,因為 .execCommand("Copy") 沒有觸發。 通過將它附加到文檔本身,並將它移到條件之外,我能夠讓它工作:

我認為這個功能更健壯:

  function selectElementContents(el) {
    var body = document.body, range, sel;
    if (document.createRange && window.getSelection) {
        range = document.createRange();
        sel = window.getSelection();
        sel.removeAllRanges();
        try {
            range.selectNodeContents(el);
            sel.addRange(range);
        } catch (e) {
            range.selectNode(el);
            sel.addRange(range);
        }
    } else if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
    document.execCommand("Copy");
}

如果您需要將表中的所有數據復制到剪貼板,則可以使用此自定義腳本; html:

<button class='btnclipboard' data-source='tableStudents'> Copy table </button>

<table id="tableStudents">
<thead>
 <th> user_id </th>
 <th> Name </th> 
</thead> 
<tbody>
 <tr>
  <td> 123 </td>
  <td> Proba </td>
 </tr>
<tbody>
</table>

<script>
    $('.btnclipboard').click(function(e) {
    e.preventDefault();
        copyTableToClipboard($(this).data('source'));
});

function copyTableToClipboard() {


var clipboard=new Clipboard('.btnclipboard',{

    text: function(trigger) {

        var txt=[];
                var headColumns = [];
                $("#tableStudents th").each(function(){
                    var textColumn = $(this).text();
                    if(textColumn == null || textColumn == "") {
                        textColumn = $(this).attr('title');
                    }
                    if(textColumn == undefined || textColumn == null) {
                        textColumn = "";
                    }
                    headColumns.push(textColumn);
                    // console.log($(this).text());
                });
                console.log('headColumns', headColumns);
                var head=headColumns;
                txt.push(head.join("\t"));

                var rowColumns=[];
                $("#tableStudents tr").each(function(){
                    var row=[];
                    $(this).find('td').each(function(){
                        var textColumn = $(this).text();
                        if($(this).find("i").hasClass('fa-check')){
                            textColumn = "1";
                        }
                        // if(textColumn == "") {
                        //  // textColumn = $(this).attr('title');
                        //  textColumn = "";
                        // }
                        // if(textColumn != null) {
                            row.push(textColumn);
                        // }
                    //console.log($(this).text());
                    });
                    if(row.length > 0) {
                        rowColumns.push(row);
                        txt.push(row.join("\t"));
                    }
                });
                console.log('rowColumns', rowColumns);
                return txt.join("\n");
    }


});

clipboard.on('success', function(e) {

    console.info('Action:', e.action);
    e.clearSelection();

    if (Notification.permission == "granted")
    {
        var notification = new Notification('Data copied to clipboard', {
            icon: '../dist/img/favicon.png',
            body: "You can now paste (Ctrl+v) into your favorite spreadsheet editor !"
        });
    }else{
        console.warn(Notification.permission);
    }
});

clipboard.on('error', function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
});
}
</script>

單擊該按鈕后,您的表數據應被復制。

我知道這是一個舊的,但如果有人仍在尋找解決方案。 這個對我有用

    <script>
    $(document).ready(function() {
        $("#copyBtn").on("click",
            function(e) {
                copyTable("listTable", e);
            });

    });

    function copyTable(el, e) {
        e.preventDefault();
        var table = document.getElementById(el);
        
        if (navigator.clipboard) {
            var text = table.innerText.trim();
            navigator.clipboard.writeText(text).catch(function () { });
        }
    }
</script>

不推薦使用所有使用execCommand的答案。

正確的答案是使用剪貼板 API,正如用戶Craig Walker在上面對這個問題的回答中所描述的那樣。 單擊此處以 go 獲得答案。

OP,請更新這篇文章並將克雷格的答案標記為正確。

function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
    range = document.createRange();
    sel = window.getSelection();
    sel.removeAllRanges();
    try {
        range.selectNodeContents(el);
        sel.addRange(range);
    } catch (e) {
        range.selectNode(el);
        sel.addRange(range);
    }
} else if (body.createTextRange) {
    range = body.createTextRange();
    range.moveToElementText(el);
    range.select();





}
CopiedTxt = document.selection.createRange();
CopiedTxt.execCommand("Copy");}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM