用javascript复制富文本

因为项目需求,但愿可以用javascript复制富文本格式的数据,例如全选一个网页Ctrl+C, Ctrl+V到一个word文档中,数据仍是原来的格式,显示出来的样子也都和原来同样。如今但愿使用javascript实现一样的功能。javascript

因为系统的限制,javascript往系统剪切板上放置的数据只有两种格式Text和URL。具体使用以下:html

function CopyToClipBoard(){     
    var clipBoardContent="abcdefg";     
    window.clipboardData.setData("Text",clipBoardContent);     
    alert("已复制本页连接,您可使用Ctrl+V粘贴后,发送给好友!");     
}    

上述方式只能存放普通的文本,没法保留原来的颜色字体大小等格式。java

 

想要复制指定对象,首先须要定位到目标对象,所幸javascript中能够根据元素的id字段进行定位,能够轻易获取组成它的html文本,可是若是把这些html数据直接放入剪切板中,用Ctrl+V进行粘贴,咱们获得的也只是没有解析的html,不能展示有效数据。浏览器

在搜索了大量资料以后终于发现了一个好的方法,经过建立ControlRange,而后执行execCommand('Copy')命令将制定元素块放到剪切板中, 此方法仅支持IE浏览器编辑器

<script>
function CopyImageToBoard(area){
if (typeof area.contentEditable == 'undefined' || !document.body.createControlRange){ alert('Your IE does not support copy action, please use ctrl + c instead! ”'); }else{ var ctr = document.body.createControlRange(); area.contentEditable = true; ctr.addElement(area); ctr.execCommand('Copy'); area.contentEditable = false; alert('Copy success! '); } }
</script>
<html>
<div id ="all">
<a href="javascript:void(0)"   onClick="CopyImageToBoard(document.getElementById('all'))" >copy to clipboard</a>
<table id="text">
  <tr style="background:red">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
 <tr style="background:green">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
 <tr style="background:black">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</div>
</html>

点击连接按钮以后会复制整个区域到系统剪切板,把数据粘贴到支持富文本格式的编辑器中如word等,就能够看到效果了。字体

相关文章
相关标签/搜索