关于在博客园文章中运行自己html

关于实现在博客网站中实时的运行自己的代码


Document

要实现代码的运行必要的条件是取到代码,并运行,在textarea中的代码中的> 或< &等都被替换了 所以使用normalizeCode 函数可以是code取出后正常

var normalizeCode = function(code){
code = code.replace(/</g,'<');
code = code.replace(/>/g,'>');
code = code.replace(/&/g,'&');
return code;
};

接下来需要将取出的代码在空白的页面运行

var runCodes = function(e){
//body点击的时候点击的元素是不是button
document.getElementsByTagName('body')[0].onclick = function(e){
var e = e || window.event;
var el=e.target|| e.srcElement;
var tag=el.nodeName.toLowerCase();
if(tag!=="button") return;
//如果是button取得data-run的值,这个值和运行的textarea的id一样的
//通过id取出textarea中的内容
var id= el.getAttribute("data-run").replace(/(^s*)|(s*$)/g,'');
var code = document.getElementById(id).innerHTML;
code = normalizeCode(code);
var newwin = window.open('', "_blank", '');//新建一个窗口
newwin.document.open('text/html', 'replace');
//第二个参数只有一个值 可选:replace,如果启用了该值,则新建的文档会覆盖当前页面的文档(相当于清空了原文档里的所有元素,且不能后退即,浏览器的后退按钮不可用);
newwin.opener = null;
newwin.document.write(code);
newwin.document.close();
}
}

这个方法比较简单,不适用一个窗口中含有多个运行的html

原文地址:https://www.cnblogs.com/heyinwangchuan/p/5813042.html