您的位置:首页 > Web前端 > HTML

通过Html实现在线运行,复制,保存代码的功能

2012-09-29 12:36 597 查看
网上找的,感觉不错正好适合博客园使用,目前测试IE能实现全部功能,chrome只能实现运行代码的功能

预览效果:

textarea

function runCode(obj) {
var winname = window.open('', "_blank", '');
winname.document.open('text/html', 'replace');
//winname.opener = null // 防止代码对原页面修改
winname.document.write(obj.value);
winname.document.close();
}
function saveCode(obj) {
var winname = window.open('', '_blank', 'top=10000');
winname.document.open('text/html', 'replace');
winname.document.writeln(obj.value);
winname.document.execCommand('saveas','','code.htm');
winname.close();
}
function copyCode(obj) {
var rng = document.body.createTextRange();
rng.moveToElementText(obj);
rng.scrollIntoView();
rng.select();
rng.execCommand("Copy");
rng.collapse(false);
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<title>测试文档</title>
</head>
<body>测试文档
</body>
</html>

提示:您可以先修改部分代码再运行

源代码复制到HTML编辑模式就可以了

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<title>textarea</title>

<script type="text/javascript">

function runCode(obj) {

var winname = window.open('', "_blank", '');

winname.document.open('text/html', 'replace');

//winname.opener = null // 防止代码对原页面修改

winname.document.write(obj.value);

winname.document.close();

}

function saveCode(obj) {

var winname = window.open('', '_blank', 'top=10000');

winname.document.open('text/html', 'replace');

winname.document.writeln(obj.value);

winname.document.execCommand('saveas','','code.htm');

winname.close();

}

function copyCode(obj) {

var rng = document.body.createTextRange();

rng.moveToElementText(obj);

rng.scrollIntoView();

rng.select();

rng.execCommand("Copy");

rng.collapse(false);

}

</script>

</head>

<body>

<textarea id="code" rows="10" cols="95">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<title>测试文档</title>

</head>

<body>测试文档

</body>

</html>

</textarea><br>

<input type="button" value="运行代码" onclick="runCode(code)"> 

<input type="button" value="复制代码" onclick="copyCode(code)"> 

<input type="button" value="另存代码" onclick="saveCode(code)"> 

提示:您可以先修改部分代码再运行<br />

</body>

</ html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐