You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

需求:实现textarea的HTML代码与预览模式切换及指定样式

实现基于textarea的HTML代码与预览模式切换功能

需求说明

  • 点击切换按钮实现两种模式切换:编辑模式(显示textarea)和预览模式(隐藏textarea,展示HTML代码渲染后的效果)
  • 界面样式:固定宽度的容器,右上角设置切换按钮,textarea占满容器大部分高度,整体样式简洁规整

完整实现代码

<!DOCTYPE html>
<html>
<head>
<style>
.container {
    width: 500px;
    position: fixed;
    border: 1px solid #ccc;
    padding: 8px;
    box-sizing: border-box;
}

.toggle-btn {
    background: #f0f0f0;
    border: 1px solid #ccc;
    padding: 4px 8px;
    cursor: pointer;
    position: absolute;
    right: 8px;
    top: 8px;
}

#preview-area {
    width: 100%;
    height: 75%;
    border: 1px solid #ccc;
    padding: 8px;
    box-sizing: border-box;
    display: none;
    overflow-y: auto;
    margin-top: 30px;
}

#w3review {
    width: 100%;
    height: 75%;
    resize: none;
    border: 1px solid #ccc;
    padding: 8px;
    box-sizing: border-box;
    margin-top: 30px;
}
</style>
</head>
<body>
<div class="container">
    <button class="toggle-btn" id="toggleBtn">Preview</button>
    <textarea id="w3review" name="w3review" >
&lt;h3&gt;At w3schools.com you will learn how to make a website. They offer free tutorials in all web development technologies.&lt;/h3&gt;
    </textarea>
    <div id="preview-area"></div>
</div>

<script>
const toggleBtn = document.getElementById('toggleBtn');
const textarea = document.getElementById('w3review');
const previewArea = document.getElementById('preview-area');

toggleBtn.addEventListener('click', function() {
    if (textarea.style.display !== 'none') {
        // 切换到预览模式
        textarea.style.display = 'none';
        previewArea.style.display = 'block';
        previewArea.innerHTML = textarea.value;
        toggleBtn.textContent = 'HTML';
    } else {
        // 切换回编辑模式
        textarea.style.display = 'block';
        previewArea.style.display = 'none';
        toggleBtn.textContent = 'Preview';
    }
});
</script>
</body>
</html>

关键说明

  • 样式统一:容器、textarea、预览区使用一致的边框和内边距,按钮固定在右上角,确保切换时视觉连贯性
  • 切换逻辑:通过按钮点击事件切换元素显示状态,同步更新按钮文本;预览模式下将textarea内容通过innerHTML渲染到预览区
  • 初始状态:默认显示编辑模式,按钮显示"Preview",点击后切换为预览模式,按钮文本变为"HTML"

内容的提问来源于stack exchange,提问作者Code Guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:11:01