看到別人部落格有運行代碼的功能不時的羨慕不已呀。想想自己經常發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;