[原] 用 javascript 给你的博客增加运行代码功能

看到别人博客有运行代码的功能不时的羡慕不已呀。想想自己经常发javascript 没有这东西怎么行,可惜我的博客又没自带这个功能,只好自己弄弄。代码比较简单,大家看看笑笑。

使用方法:
<textarea class="runCode">要运行的代码</textarea>

这里看看效果 http://dubox.cn/content-26.aspx

  function  page_Init() {
  
var obj=document.getElementsByTagName("textarea");
    
for(i=0;i<obj.length;i++){
      
if(obj[i].className=="runCode"){
         
var _temid="code_"+i;
         
        
         
var html="<textArea style=\"width:80%;height:200px;border-width:1px;border-style:inset\" id=\""+_temid+"\">";
             html
+=obj[i].value;
             html
+="</textArea><br>";
             html
+="<input type=\"button\" value=\"运行代码\" onClick=\"run('"+_temid+"')\" style=\"border-width:1px\"/><em>(提示:您可以修改代码后运行)</em>";
         
var newobj=document.createElement("div");
             newobj.style.border
="1px solid #c0c0c0";
             newobj.style.backgroundColor
="#f5f7f7";
             newobj.style.padding
="10px";
             newobj.innerHTML
=html;
             
             
              if(document.all){
             obj[i].replaceNode(newobj);
             }else{
             obj[i].parentNode.replaceChild(newobj,obj[i]); 
             }

             
      }

    }

 }

 
function  run(string_id) {
 
var _code=document.getElementById(string_id).value;
 
var win = window.open('', "_blank", '');
        win.document.open('text
/html', 'replace');
        win.document.writeln(_code);
 }


window.onload
= page_Init;

 

你可能感兴趣的:(JavaScript)