DIV CSS 佈局教程網

實現網頁中「運行代碼」功能的思路
編輯:關於JavaScript     

許多技術部落格都提供「運行代碼」的功能,讓讀者能直接在網頁上編輯並執行 HTML 片段。它的實作原理其實很單純:把文字方塊裡的內容寫入一個新開啟的視窗文件中,再讓瀏覽器渲染即可。

參考程式碼 如下:

<!DOCTYPE html>
<html>
<head>
<meta charset='utf8' />
<title>網頁中的運行代碼功能</title>
<script type="text/javascript">
function runCode(oCode) {
var win = window.open('', "_blank", '');
win.document.open('text/html', 'replace');
win.opener = null
win.document.write(oCode.value);
win.document.close();
}
</script>
</head>
<body>
<textarea id="code1" rows="10" cols="95">
<!DOCTYPE html>
<html>
<head>
<meta charset='utf8' />
<title>測試文檔</title>
</head>
<body>
測試文檔 - 你可以先修改部分代碼再運行
<script>alert('hello')</script>
</body>
</html>
</textarea>
<br>
<input type="button" value="運行代碼" onclick="runCode(code1)">
</body>
</html>

核心的 runCode 函式做了幾件事:先用 window.open 開啟一個新視窗,接著以 document.open 開啟寫入模式,把文字方塊的值透過 document.write 寫進去,最後用 document.close 結束寫入並觸發渲染。其中 win.opener = null 這句相當重要,它斷開新視窗與原視窗的 opener 關聯,避免被寫入的內容透過 window.opener 反向操作原頁面,這是一個基本的安全防護。

透過這種方式,讀者就能在文字方塊中隨意修改程式碼並按下按鈕即時預覽效果,非常適合製作線上程式碼教學與展示。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved