我正在尝试将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!';
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句