<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>在线编辑HTML</title>
<style>
/* 简单的样式,使编辑器看起来更友好 */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
height: 100vh;
}
.editor, .preview {
width: 50%;
height: 100%;
box-sizing: border-box;
}
.editor {
border-right: 1px solid #ccc;
}
textarea {
width: 100%;
height: 100%;
border: none;
outline: none;
padding: 10px;
box-sizing: border-box;
resize: none;
}
iframe {
width: 100%;
height: 100%;
border: none;
}
</style>
</head>
<body>
<div class="editor">
<textarea id="html-editor" placeholder="在这里编写HTML代码"></textarea>
</div>
<div class="preview">
<iframe id="html-preview"></iframe>
</div>
<script>
// 获取编辑器和预览框的DOM元素
const editor = document.getElementById('html-editor');
const preview = document.getElementById('html-preview');
// 监听编辑器内容的变化,并实时更新预览
editor.addEventListener('input', function() {
preview.contentDocument.body.innerHTML = editor.value;
});
</script>
</body>
</html>
HTML结构:
textarea),右边是HTML预览(iframe)。CSS样式:
JavaScript功能:
addEventListener监听textarea中的输入变化,每当用户在编辑器中输入或修改HTML代码时,立即更新iframe中的内容以实现实时预览。通过这个示例代码,你可以创建一个简单的在线HTML编辑器,用户可以在左侧编写HTML代码,右侧会实时显示渲染效果。
上一篇:html外边距
下一篇:html 文本标签
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站