copy whole html table to clipboard javascript

前端 未结 8 1647
暗喜
暗喜 2021-01-05 06:58

I have write javascript to select the table but I want to now automaticaly copy it after the click of the button.Please help me.My javascript is like this.

f         


        
8条回答
  •  说谎
    说谎 (楼主)
    2021-01-05 07:33

    The previous scripts did not work for me because the .execCommand("Copy") was not triggering. By attaching it to the document itself, and moving it outside of the conditional, I was able to get it to work:

    I think this function is more robust:

      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");
    }
    

提交回复
热议问题