繁体   English   中英

javascript将元素复制到具有所有样式的剪贴板

[英]javascript copy element to clipboard with all styles

我正在尝试将 div 复制到剪贴板。 div 有几种样式,包括background 我已经制作了一个脚本来将 div 复制到剪贴板,但我不知道如何做背景。

我见过这样做,但我不记得是怎么做的。

任何帮助将不胜感激。


这是我得到的:

 function executeCopy(text) { var copyDiv = document.createElement('div'); copyDiv.contentEditable = true; document.body.appendChild(copyDiv); copyDiv.innerHTML = text; copyDiv.unselectable = "off"; copyDiv.focus(); document.execCommand('SelectAll'); document.execCommand("Copy", false, null); document.body.removeChild(copyDiv); }
 #foo { background-color: red; font-family: cursive; }
 <div id="foo">Test</div> <button onclick="executeCopy(document.getElementById('foo').innerHTML);">Copy</button>

您可以尝试以下小提琴。 它适用于所有文本样式,并且可以与 MS Word 和 Pages 互操作(我刚刚测试过)。

代码非常简单,所以我不会真正深入它,但是如果您有任何问题,请随时向我提出。 :)

const copyWithStyle = ( element ) => {

    const doc = document;
    const text = doc.getElementById( element );
    let range;
    let selection;

    if( doc.body.createTextRange ) {

        range = doc.body.createTextRange();
        range.moveToElement( text );
        range.select();

    } else if ( window.getSelection ) {

        selection = window.getSelection();

        range = doc.createRange();
        range.selectNodeContents( text );

        selection.removeAllRanges();
        selection.addRange( range );

    }

    document.execCommand( 'copy' );
    window.getSelection().removeAllRanges();
    document.getElementById( 'clickMe' ).value = 'Copied to clipboard!';

}

https://jsfiddle.net/aypdg3kL/

来自 JSFiddle 中的示例

HTML

<div id="text" style="color:red">
    <i>Hello</i> world!
</div>
<input id="btn" onclick="CopyToClipboard('text')" type="button" value="Copy" />

JS

function CopyToClipboard(element) {

        var doc = document
        , text = doc.getElementById(element)
        , range, selection;
    
    if (doc.body.createTextRange)
    {
        range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } 
    
    else if (window.getSelection)
    {
        selection = window.getSelection();        
        range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    document.getElementById("btn").value="Copied";
}

暂无
暂无

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

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