HTML5 blob实现JS,CSS,HTML直接当前页预览
术后闲看,看到张鑫旭大神写的iframe和HTML5 blob实现JS,CSS,HTML直接当前页预览,之前还真没这么用过,简单测试了一下,还蛮好用。
例如下面代码:
div.haorooms {
position: absolute; top: 50px; left: 50px;
-webkit-animation: clockwise 2.5s linear infinite; animation: clockwise 2.5s linear infinite ;
transform-origin: 70px 70px;
}
.haorooms em {
display: block;
width: 40px; height: 40px;
background: red;
color:000;
-webkit-animation: counter-clockwise 2.5s linear infinite; animation: counter-clockwise 2.5s linear infinite ;
}
@-webkit-keyframes clockwise{
0% { -webkit-transform: rotate(0deg) ; }
100%{ -webkit-transform: rotate(360deg); }
}
@keyframes clockwise {
0% { transform: rotate(0deg) ; }
100%{ transform: rotate(360deg); }
}
@-webkit-keyframes counter-clockwise {
0% { -webkit-transform: rotate(360deg) ; }
100%{ -webkit-transform: rotate(0deg); }
}
@keyframes counter-clockwise {
0% { transform: rotate(360deg) ; }
100%{ transform: rotate(0deg); }
}
<textarea name="" id="preid" style="display: none">
<br />
<style>
div.haorooms {
position: absolute; top: 50px; left: 50px;
-webkit-animation: clockwise 2.5s linear infinite; animation: clockwise 2.5s linear infinite ;
transform-origin: 70px 70px;
}
.haorooms em {
display: block;
width: 40px; height: 40px;
background: red;
color:000;
-webkit-animation: counter-clockwise 2.5s linear infinite; animation: counter-clockwise 2.5s linear infinite ;
}
@-webkit-keyframes clockwise{
0% { -webkit-transform: rotate(0deg) ; }
100%{ -webkit-transform: rotate(360deg); }
}
@keyframes clockwise {
0% { transform: rotate(0deg) ; }
100%{ transform: rotate(360deg); }
}
@-webkit-keyframes counter-clockwise {
0% { -webkit-transform: rotate(360deg) ; }
100%{ -webkit-transform: rotate(0deg); }
}
@keyframes counter-clockwise {
0% { transform: rotate(360deg) ; }
100%{ transform: rotate(0deg); }
}
</style>
<div class="haorooms">
<em>haorooms</em>
</div>
</textarea>
案例效果预览
<script>
var btn =document.getElementById("btn-run");
btn.onclick = function() {
var iframe = document.createElement('iframe');
iframe.setAttribute('style', 'width:400px;max-width:68%;max-height:300px;height:38vh;position:fixed;border:1px solid;outline:9999px solid rgba(0,0,0,.6);top:0;right:0;left:0;bottom:0;margin:auto;overflow:hidden;background:#fff');
iframe.src = URL.createObjectURL(new Blob([document.getElementById('preid').value],{"type":"text/html"}));
document.codeIframe=iframe;
document.body.appendChild(document.codeIframe);
};
document.body.addEventListener('mouseup', function() {
if (document.codeIframe){
document.body.removeChild(document.codeIframe);
document.codeIframe=null;
}
});
</script>
核心原理:
1、创建iframe元素;
2、将CSS,HTML字符串转换为Blob对象;
3、使用URL.createObjectURL()方法将Blob对象转换为URL对象并赋予我们创建的iframe元素的src属性;
核心js如下:
// 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);