文章详情
html实时网页代码编写测试实时浏览
Posted on 2023-11-24 03:33:39 by 主打一个C++
测试使用了手机模型代码效果图:
html代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实时网页代码浏览测试</title>
</head>
<body>
<main>
<div id="preview">
<h2>实时预览<span class="hide-editorx-btn" onclick="hidecode(this);" title="显示/隐藏代码区">》</span></h2>
<hr>
<iframe id="previewFrame" name="previewFrame"></iframe>
</div>
<div id="editor">
<h2>代码区</h2>
<hr>
<textarea id="htmlCode" name="htmlCode" placeholder="HTML/css/js等代码,支持多种语言混合解析"></textarea>
<textarea id="cssCode" name="cssCode" placeholder="扩展css代码"></textarea>
</div>
</main>
</body>
</html>
css样式:
<style>
body {
font-family: Arial, sans-serif;
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
main {
display: flex;
justify-content: left;
width: 100%;
height: 100%;
box-sizing: border-box;
}
#editor {
width: 100%;
height: 100%;
border-right: 1px solid #ccc;
text-align: center;
box-sizing: border-box;
}
.editor-title {
display: flex;
justify-content: center;
align-items: center;
}
.hide-editorx-btn {
background-color: transparent;
float: right;cursor: pointer;
}
.hide-editorx-btn:hover{
color: red;
}
#preview {
width: 100%;
height: 100%;
border: 0px solid #000;
border-right-width: 1px;
text-align: center;
box-sizing: border-box;
}
textarea {
width: 100%;
height: 50vh;
border: 0px solid #000;
border-bottom-width: 1px !important;
resize: none;
font-family: 'Courier New', Courier, monospace;
padding: 5px;
box-sizing: border-box;
}
iframe {
width: 100%;
height: 100vh;
border: none;
}
/* 设置滚动条颜色 */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-thumb {
background-color: #ccc;
border-radius: 4px;
}
::-webkit-scrollbar-track {
background-color: #f1f1f1;
}
</style>
js代码:
<script>
function hidecode(_this) {
const editor = document.getElementById('editor');
if (editor.style.display === 'none') {
editor.style.display = 'block';
_this.innerHTML = '》';
} else {
editor.style.display = 'none';
_this.innerHTML = '《 ';
}
}
function updatePreview() {
const htmlCode = document.getElementById('htmlCode').value;
const cssCode = document.getElementById('cssCode').value;
const previewFrame = document.getElementById('previewFrame').contentDocument || document.getElementById('previewFrame').contentWindow.document;
previewFrame.open();
previewFrame.write('<html><head><style>' + cssCode + '</style></head><body>' + htmlCode + '</body></html>');
previewFrame.close();
}
document.getElementById('htmlCode').addEventListener('input', updatePreview);
document.getElementById('cssCode').addEventListener('input', updatePreview);
</script>
*转载请注明出处:原文链接:https://cpp.vin/page/117.html