在网页上加入运行代码的功能
生活随笔
收集整理的這篇文章主要介紹了
在网页上加入运行代码的功能
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
經(jīng)常看到別人的博客或介紹html/css/js的網(wǎng)站上有個功能是運行代碼 它是如何實現(xiàn)的 下面就一起來寫一下
最基本的實現(xiàn)方式是 打開一個新的窗口 向里面寫入html代碼它就會自動執(zhí)行
var win = window.open('', "_blank", '');
win.document.open('text/html', 'replace');
win.opener = null;
win.document.write(code);
win.document.close();
這樣直接把code寫入到新窗口就可以了
但是直接寫入的HTML會直接顯示在頁面上 而不是由瀏覽器渲染后生成的 這是為什么?
因為"< > & "這些個的存在 所以需要轉(zhuǎn)義一下
var normalizeCode = function (code) {
code = code.replace(/</g, '<');
code = code.replace(/>/g, '>');
code = code.replace(/&/g, '&');
return code;
};
接下來就沒什么問題了
<!DOCTYPE html>
<html>
<head>
<title>運行代碼</title>
</head>
<body>
<textarea id="code">
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>測試</title>
</head>
<body>
<h1>測試一下</h1>
</body>
</html>
</textarea>
<button id="btn">運行</button>
<script>
var normalizeCode = function (code) {
code = code.replace(/</g, '<');
code = code.replace(/>/g, '>');
code = code.replace(/&/g, '&');
return code;
};
var runCode = function () {
//innerHTML需要轉(zhuǎn)義
var code = document.getElementById('code').innerHTML;
//value不需要轉(zhuǎn)義 但是在博客園上不能直接寫value 它會給你轉(zhuǎn)義
//var code = document.getElementById('code').value;
if (code != "") {
console.log(code);
code = normalizeCode(code);
console.log(code);
var win = window.open('', "_blank", '');
win.document.open('text/html', 'replace');
win.opener = null;
win.document.write(code);
win.document.close();
}
};
var btn = document.getElementById('btn');
btn.addEventListener('click', runCode, false);
</script>
</body>
</html>
實驗一下 因為是使用textarea 的innerHTML 所以不能通過修改下面的代碼來達(dá)到修改運行結(jié)果的效果 可使用textarea的value屬性
我們肯定使用過W3School的在線測試工具 下面來做一個差不多的東西
<!DOCTYPE html>
<html>
<head>
<title>運行代碼</title>
</head>
<body>
<textarea id="code">
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>測試</title>
</head>
<body>
<h1>測試一下</h1>
<script>
document.write("哈哈哈");
</script>
</body>
</html>
</textarea>
<iframe name="run"></iframe>
<button id="btn">運行</button>
<script>
var normalizeCode = function (code) {
code = code.replace(/</g, '<');
code = code.replace(/>/g, '>');
code = code.replace(/&/g, '&');
return code;
};
var runCode = function () {
var code = document.getElementById('code').value;
if (code != "") {
console.log(code);
code = normalizeCode(code);
console.log(code);
var win = window.open('', "run", '');
win.document.open('text/html', 'replace');
win.opener = null;
win.document.write(code);
win.document.close();
}
};
var btn = document.getElementById('btn');
btn.addEventListener('click', runCode, false);
</script>
</body>
</html>
效果如下
Copy一下到本地 自己試一下吧
總結(jié)
以上是生活随笔為你收集整理的在网页上加入运行代码的功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [原创]OpenEuler20.03安装
- 下一篇: java设计优化--代理模式