Skip to content
鼓励作者:欢迎打赏犒劳

代码预览

手动实现代码预览

比如我们有时候会看到有一些网站展示源代码,同时也会有代码展示,特效什么的,如何实现的呢。个人感觉最好还是嵌入一个iframe

html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div>
    <div>
        <textarea name="" id="code" style="width: 100%" cols="30" rows="10"></textarea>
    </div>
    <div><button onclick="yulan()">预览</button></div>
    <div id="c">
    </div>
</div>

<script>
    function yulan() {
        let ele = document.getElementById('code');
        // 1. 创建<iframe>元素
        let iframe = document.createElement('iframe');
        // 2. 将CSS,HTML字符串转换为Blob对象
        let htmlCode = ele.value
        let blob = new Blob([htmlCode], {
            'type': 'text/html'
        });
        // 3. 使用URL.createObjectURL()方法将...
        iframe.src = URL.createObjectURL(blob);
        //设置iframe无边框
        iframe.style.border = 'none';
        iframe.style.width = '100%'
        // iframe.style.height = '400px'
        iframe.onload = autoResize;
        //去掉滚动条
        iframe.scrolling = "no";

        document.getElementById('c').innerHTML = ''
        document.getElementById('c').appendChild(iframe);
    }
    function autoResize() {
        const iframe =document.querySelector('iframe');
        const iframeDocument = iframe.contentWindow.document;
        const iframeHeight = iframeDocument.documentElement.scrollHeight;
        const iframeWidth = iframeDocument.documentElement.scrollWidth;
        console.log('iframeHeight : '+ iframeHeight)
        console.log('iframeWidth : '+ iframeWidth)
        iframe.style.height = iframeHeight + 'px'
    }
</script>
</body>
</html>

如有转载或 CV 的请标注本站原文地址