简单实现HTML在线编辑器

        我们继续来看一下如何开发一个简单的html在线编辑器,要求很简单 能够同时编辑html,css,js代码,并且运行之后可以同时预览效果


一:前置知识

        在H5中设置了一个新的标签,

(2)css

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
}
html, body {
    height: 100%;
}

body{
    background-color: #454545;
    display: flex;
}
/* 左 */
.left{
    width: 50vw;
    height: 100%;
    /* background-color: pink; */
    padding: 5vh;
}
.left .html{
    width: 100%;
    height: 30vh;
    border-radius: 5px;
    background-color: #fff;
    margin-bottom: 1vh;
    display: flex;
    flex-direction: column;
    position: relative;
}
.run-html{
    transform: translate(-110%, -110%);
    top: 100%;
    left: 100%;
    position: absolute;
    width: 10vh;
    border-radius: 2vh;
    background-color: #95e330;
}
.run-html:hover{
    background-color: #88d228;
}
.run-html:active{
    background-color: #78c220;
}
.left .css{
    width: 100%;
    height: 30vh;
    border-radius: 5px;
    background-color: #fff;
    margin-bottom: 1vh;
    display: flex;
    flex-direction: column;

}
.left .js{
    width: 100%;
    height: 30vh;
    border-radius: 5px;
    background-color: #fff;
    margin-bottom: 1vh;
    display: flex;
    flex-direction: column;

}
.left .title{
    width: 100%;
    text-align: center;
    border: 0.5px solid #ccc;
}
.left textarea{
    padding: 2px;
    width: 100%;
    height: 100%;
    border: 0;
    box-sizing: border-box;
    flex-grow: 1;
    background-color: #ccc;
}

.left textarea:focus {
    /* 点击输入框不会出现黑边 */
    outline: none;
}
/* 右 */
.right{
    width: 50vw;
    height: 100%;
    /* background-color: skyblue; */
    padding: 5vh;
}

.right .show{
    width: 100%;
    height: 92vh;
    background-color: #fff;
}

.right .title{
    width: 100%;
    text-align: center;
    border: 0.5px solid #ccc;
}

.right iframe{
    width: 100%;
    height: 100%;
}

(3)js

const html=document.querySelector('.htmlInput');
const css=document.querySelector('.cssInput');
const js=document.querySelector('.jsInput');

const btnhtml=document.querySelector('.run-html');
const output=document.querySelector('.show iframe');
function run(){
    output.contentDocument.body.innerHTML = html.value + '';
    const script = output.contentDocument.createElement('script');
    script.textContent = js.value;
    output.contentDocument.body.appendChild(script);
}
btnhtml.addEventListener('click',run);

就这样吧 实现这个功能如果利用这个iframe标签的话就非常简单了

你可能感兴趣的:(html,编辑器,前端)