前端几行代码简单实现w3school代码预览

原文链接

w3school案例

demo地址

代码很简单,利用URL.createObjectURL生成url赋给iframe,就可以不借助服务器实现代码预览了。

demo截图

demo截图

直接看代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
    <style>
        html,
        body {
            height: 100%;
        }
        .title-wrapper,
        .code-wrapper {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        h2.title {
            width: 50%;
            color: red;
            padding: 0 20px;
            font-size: 14px;
        }
        .code-wrapper {
            width: 100%;
            height: 100%;
        }
        .previewBtn {
            display: inline-block;
            padding: 5px 30px;
            background-color: red;
            color: #fff;
            text-decoration: none;
        }
        .code,
        .preview-container {
            width: 50%;
            height: 100%;
            overflow: hidden;
            border: 1px solid #ccc;
        }
        .code {
            margin-right: 10px;
        }
        .code textarea {
            width: 100%;
            height: 100%;
            white-space: pre;
            resize: none;
            border: none;
            outline: none;
        }
        .preview-container .preview {
            width: 100%;
            height: 100%;
        }
        .preview-container iframe {
            display: block;
            border: none;
            outline: none;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <p>
        <a class="previewBtn" href="javascript:;" onclick="onPreview()">预览</a>
    </p>
    <div class="title-wrapper">
        <h2 class="title">编辑代码:</h2>
        <h2 class="title">查看效果:</h2>
    </div>
    <div class="code-wrapper">
        <div class="code">
            <textarea class="js-code"></textarea>
        </div>
        <div class="preview-container">
            <div class="preview js-preview"></div>
        </div>
    </div>
<script>
    function onPreview () {
        var code = $('.js-code').val(),  //获取代码字符串
            $preview = $('.js-preview'), 
            blob = new Blob([code], {  //注意一定要写type
                'type': 'text/html'
            }),
            url = URL.createObjectURL(blob), //生成url
            $iframe = $('<iframe src="' + url + '"></iframe>');
        $preview.html('').append($iframe);
    }
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
最近更新: 9/13/2020, 10:47:04 PM