实现一个在线编辑html,css,js代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online HTML/CSS/JS Editor</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
height: 100vh;
margin: 0;
}
.editor-container {
display: flex;
flex: 1;
padding: 10px;
}
.editor {
flex: 1;
margin: 5px;
display: flex;
flex-direction: column;
}
textarea {
flex: 1;
padding: 10px;
font-family: monospace;
font-size: 14px;
resize: none;
}
#result {
flex: 1;
margin: 5px;
border: 1px solid #ccc;
overflow: auto;
}
.header {
padding: 10px;
background: #f1f1f1;
border-bottom: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="header">
<button id="runButton">Run</button>
</div>
<div class="editor-container">
<div class="editor">
<h3>HTML</h3>
<textarea id="htmlCode"><h1 id="text">Hello, World!</h1></textarea>
</div>
<div class="editor">
<h3>CSS</h3>
<textarea id="cssCode">h1 { color: blue; }</textarea>
</div>
<div class="editor">
<h3>JavaScript</h3>
<textarea id="jsCode">
console.log('Hello, World from iframe!');
</textarea>
</div>
<iframe id="result"></iframe>
</div>
<script>
const runCode = () => {
try {
const htmlCode = document.getElementById('htmlCode').value;
const cssCode = document.getElementById('cssCode').value;
let jsCode = document.getElementById('jsCode').value;
jsCode = jsCode.replace(/console\.log\((.*?)\);?/g, "window.parent.displayOutput($1);");
const resultFrame = document.getElementById('result');
let iframeDoc = resultFrame.contentDocument || resultFrame.contentWindow.document;
iframeDoc.head.innerHTML = `<style>${cssCode}</style>`;
iframeDoc.body.innerHTML = htmlCode;
const script = iframeDoc.createElement('script');
script.textContent = jsCode
iframeDoc.body.appendChild(script);
} catch (error) {
console.error("Error:", error);
}
};
document.getElementById('runButton').addEventListener('click', runCode);
function displayOutput(output) {
const outputArea = document.getElementById('output');
outputArea.textContent += output + '\n';
}
</script>
<div class="header">
<h3>Output</h3>
</div>
<div id="output" style="overflow: auto; height: 100px;"></div>
</body>
</html>