码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript运行网页中的代码,保存网页中的代码

时间:2016-04-11 18:41:20      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE html>
<html>
<head>
    <title>在网页中运行代码,保存代码</title>
    <meta charset="utf-8">
</head>
<body>
    <textarea id="code" style="width: 500px;height: 300px">
        &lt;html&gt;
        &lt;head&gt;
            &lt;meta charset="UTF-8"&gt;
            &lt;title&gt;Document&lt;/title&gt;
            &lt;style type="text/css"&gt;
        div {
            margin: 0 auto;
            width: 100px;
            height: 100px;
            border: 5px groove #f00;
            outline: 5px outset #0f0;
        }
            &lt;/style&gt;
        &lt;/head&gt;
        &lt;body&gt;
            &lt;div&gt;&lt;em&gt;1&lt;/em&gt;&lt;/div&gt;
        &lt;/body&gt;
        &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"&gt;&lt;/script&gt;
        &lt;/html&gt;
    </textarea>
    <br>
    <button onclick="runCode(document.getElementById(‘code‘).value)">运行代码</button>
    <button onclick="saveCode(document.getElementById(‘code‘).value, ‘save‘)">保存代码</button>
</body>
<script>
    // 运行代码
    function runCode(code) {
        var newWindow = window.open(‘‘, ‘‘, ‘‘);
        newWindow.opener = null;
        newWindow.document.write(code);
        newWindow.document.close();
    }
 
    // 保存代码
    function saveCode(code, filename) {
        if (/msie/i.test(navigator.userAgent)) {
            var newwin = window.open(‘‘, _blank, top=10000);
            newwin.document.open(text/html, replace);
            newwin.document.write(code);
            newwin.document.execCommand(saveas, ‘‘, filename + .html);
            newwin.close();
        } else {
            var a = document.createElement(a),
                r1 = /<meta.*?charset\=.*\>/i,
                r2 = /<meta.*?charset\=.*\> /i,
                r3 = /<meta.*?charset\=.*\></i;
 
            if (r1.test(code)) {
                code = code.replace(r1, ‘‘);
            } else if (r2.test(code)) {
                code = code.replace(r2, ‘‘);
            } else if (r3.test(code)) {
                code = code.replace(r3, <);
            }
            a.href = data:text/html;charset=utf8, + code;
            a.download = filename + .html;
            a.click();
        }
    }
</script>
</html>

 

JavaScript运行网页中的代码,保存网页中的代码

标签:

原文地址:http://www.cnblogs.com/happyfreelife/p/5379292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!