通过JavaScript脚本复制网页上的一个表格

<INPUT TYPE="button" value="复制测试表格" οnclick="CopyTable()">
<INPUT TYPE="button" value="将剪切板内容输出到编辑器中" οnclick="PastClipboardData()"><BR>
测试
<TABLE border="1" id="oTable">
<TR>
 <TD>测试表格</TD>
 <TD>测试表格</TD>
</TR>
<TR>
 <TD>测试表格</TD>
 <TD>测试表格</TD>
</TR>
</TABLE>文字<BR><BR>
<iframe id="editor" src="about:blank"></iframe>
<SCRIPT LANGUAGE="JavaScript">
<!--
function CopyTable()
{
 CopyHtmlElement(oTable)
}
 
function CopyHtmlElement(obj)
{
 editor.document.designMode = 'On'; // 将iframe变成可编辑模式,即HTML编辑器
 editor.document.write("<body></body>");  // 初始化编辑器
 editor.document.body.innerHTML = obj.outerHTML;
 editor.document.body.createTextRange().select(); // 选中编辑器内所有内容
 editor.document.execCommand("copy","",null); // 复制
}
function PastClipboardData()
{
 editor.focus();
 editor.document.execCommand("paste","",null); // 粘贴
}
-->
</SCRIPT>

这样子功能是实现了,不过觉得有点不爽,必须借助HTML编辑器才可,不过从全选HTML编辑器的代码中,注意到了createTextRange()方法,这个方法以前就有用过,只是一直没深入研究过。在Msdn中发现只有Body、TextArea等对象支持createTextRange()方法,继续在msdn中仔细查阅了一下,createTextRange()返回的是一个 TextRange 对象,继续查阅 TextRange对象,发现其有很多方法,先试了试findText方法,发现只能选中文字,不能选中对象,继续找,终于发现了moveToElementText就是我们要找的方法:


<INPUT TYPE="button" value="选中测试表格" οnclick="CopyTable()">
测试
<TABLE border="1" id="oTable">
<TR>
 <TD>测试表格</TD>
 <TD>测试表格</TD>
</TR>
<TR>
 <TD>测试表格</TD>
 <TD>测试表格</TD>
</TR>
</TABLE>文字
<SCRIPT LANGUAGE="JavaScript">
<!--
function CopyTable()
{
 var txt = document.body.createTextRange();
 txt.moveToElementText(oTable);
 txt.select();
}
-->
</SCRIPT>

猜你喜欢

转载自blog.csdn.net/cqn2bd2b/article/details/126635648