iframe和HTML5 blob实现JS,CSS,HTML直接当前页预览

原理:

此效果实现的核心原理是:

  1. 创建<iframe>元素;
  2. 将CSS,HTML字符串转换为Blob对象;
  3. 使用URL.createObjectURL()方法将Blob对象转换为URL对象并赋予我们创建的<iframe>元素的src属性;

使用JavaScript代码表示更加一目了然:

// 1. 创建<iframe>元素
var iframe = document.createElement('iframe');
// 2. 将CSS,HTML字符串转换为Blob对象
var blob = new Blob([htmlCode], {
  'type': 'text/html'
});
// 3. 使用URL.createObjectURL()方法将...
iframe.src = URL.createObjectURL(blob);

需要注意的是,当我们使用 new Blob() 对我们的字符数据进行转换的时候,一定要指定typetext/html,否则,HTML代码会被自动转移为安全的纯文本显示在<iframe>元素中。

兼容性
IE浏览器遗憾并不支持src直接是URL对象。

所以此技术只适用于对兼容性没有严格要求的一些项目。

示例代码:

<!DOCTYPE html>
< html lang= "en">

< head>
< meta charset= "UTF-8">
< meta name= "viewport" content= "width=device-width, initial-scale=1.0">
< meta http-equiv= "X-UA-Compatible" content= "ie=edge">
< title>Document</ title>
< style>
.show {
width: 600 px;
height: 600 px;
margin: auto;
position: absolute;
top: 10 px;
right: 0;
z-index: 2;
}
.show iframe {
width: 100 %;
height: 100 %;

}
</ style>
</ head>

< body>
< div>
< h4>示例代码</ h4>
< button>运行</ button>
< pre>
< script type= "text/html" style= "display: block;" id= "code1">
< style>
html {
height: 100 vh;
}
body {
height: inherit;
background: #2e576b;
display: -ms-grid;
display: grid;
}
.container {
margin: auto;
}
.card {
position: relative;
width: 300 px; height: 350 px;
background: #fff;
border-radius: 2 px;
box-shadow: 0 2 px 15 px 3 px rgba( 0, 0, 0, 0.08);
overflow: hidden;
}
.card::after {
content: '';
display: block;
width: 100 %; height: 100 %;
background: linear-gradient( to bottom, #0065a8, rgba( 221, 238, 255, 0.4) 46 %, rgba( 255, 255, 255, 0.5));
}
.wave {
position: absolute;
top: 3 %; left: 50 %;
width: 400 px; height: 400 px;
margin-top: -200 px; margin-left: -200 px;
background: #0af;
border-radius: 40 %;
opacity: .4;
animation: shift 3 s infinite linear;
}
.wave.w2 {
background: yellow;
opacity: .1;
animation: shift 7 s infinite linear;
}
.wave.w3 {
animation: shift 5 s infinite linear;
background: crimson;
opacity: 0.1;
}
@-webkit-keyframes shift {
from {
transform: rotate( 360 deg);
}
}
@keyframes shift {
from {
transform: rotate( 360 deg);
}
}
</ style>
< div class= "container">
< div class= "card">
< div class= "wave w1"></ div>
< div class= "wave w2"></ div>
< div class= "wave w3"></ div>
</ div>
</ div>
</ script>
</ pre>
< div class= "show">

</ div>

</ div>
</ body>
< script>
var btn = document. getElementsByTagName( "button")[ 0];
var htmlCode = document. getElementById( "code1").innerHTML;
var showDom = document. getElementsByClassName( "show")[ 0];

btn. onclick = function ( param) {
var blob = new Blob([htmlCode],{type: "text/html"});
var iframeDom = document. createElement( "iframe");
iframeDom.src = URL. createObjectURL(blob);
showDom. appendChild(iframeDom);
}
</ script>

</ html>

猜你喜欢

转载自blog.csdn.net/itzhongzi/article/details/79666662