标签:
<!DOCTYPE html>
<html>
<head>
<title>在网页中运行代码,保存代码</title>
<meta charset="utf-8">
</head>
<body>
<textarea id="code" style="width: 500px;height: 300px">
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div {
margin: 0 auto;
width: 100px;
height: 100px;
border: 5px groove #f00;
outline: 5px outset #0f0;
}
</style>
</head>
<body>
<div><em>1</em></div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</html>
</textarea>
<br>
<button onclick="runCode(document.getElementById(‘code‘).value)">运行代码</button>
<button onclick="saveCode(document.getElementById(‘code‘).value, ‘save‘)">保存代码</button>
</body>
<script>
// 运行代码
function runCode(code) {
var newWindow = window.open(‘‘, ‘‘, ‘‘);
newWindow.opener = null;
newWindow.document.write(code);
newWindow.document.close();
}
// 保存代码
function saveCode(code, filename) {
if (/msie/i.test(navigator.userAgent)) {
var newwin = window.open(‘‘, ‘_blank‘, ‘top=10000‘);
newwin.document.open(‘text/html‘, ‘replace‘);
newwin.document.write(code);
newwin.document.execCommand(‘saveas‘, ‘‘, filename + ‘.html‘);
newwin.close();
} else {
var a = document.createElement(‘a‘),
r1 = /<meta.*?charset\=.*\>/i,
r2 = /<meta.*?charset\=.*\> /i,
r3 = /<meta.*?charset\=.*\></i;
if (r1.test(code)) {
code = code.replace(r1, ‘‘);
} else if (r2.test(code)) {
code = code.replace(r2, ‘‘);
} else if (r3.test(code)) {
code = code.replace(r3, ‘<‘);
}
a.href = ‘data:text/html;charset=utf8,‘ + code;
a.download = filename + ‘.html‘;
a.click();
}
}
</script>
</html>
标签:
原文地址:http://www.cnblogs.com/happyfreelife/p/5379292.html