<!DOCTYPE html> <html> <head> <meta charset="gb2312" /> <title>runcode-运行HTML/CSS/Jvascrip代码</title> </head> <body> <form> <textarea name="codearea" style="width:800px; height:600px"> </textarea> <br /> <input name="run" type="button" value="运行代码"> </form> <script> (function(){ function run(code){ var newWin = window.open("", "_blank", ""); newWin.opener = null; // 防止代码对页面修改 newWin.document.open(); newWin.document.write(code); newWin.document.close(); } //遍历页面中运行代码按钮 var executes = document.getElementsByName("run"); for(var i=0; i<executes.length; i++){ executes[i].onclick = function(){ var code = this.form.codearea.value; run(code); }; } }()); </script> </body> </html>
要在博客中插入可运行的代码:
一 将博客园后台的文本编辑器切换到的HTML视图下插入代码:
<form> <textarea name="codearea" style="width:800px; height:600px"> </textarea> <br /> <input name="run" type="button" value="运行代码"> </form>
表单元素的样式可以根据需要调整。
二 、在textarea中插入需要运行的代码,代码需要经过HTML ENCODE 否则提交的时候会被处理。
三、在页面底部加入代码:
<script type="text/javascript" src="http://www.buyed.cn/blog/script/runcode.js"></script>
或者拷贝runcode.js中的代码到页面上。
演示: