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

VueJS实现单textarea内Markdown语法高亮的技术求助

实现VueJS + highlight.js单区域Markdown语法高亮输入

核心思路是通过层叠布局将输入控件和高亮展示层合并:用透明的<textarea>负责接收用户输入,下层叠加<pre>渲染highlight.js处理后的Markdown高亮内容,视觉上呈现为同一个输入区域。

完整实现代码

<template>
  <div class="markdown-editor">
    <textarea 
      v-model="code" 
      class="editor-input"
      spellcheck="false"
    ></textarea>
    <pre class="editor-highlight hljs" v-html="highlightedCode"></pre>
  </div>
</template>

<script>
import hljs from 'highlight.js/lib/core';
import 'highlight.js/styles/monokai-sublime.css';
import markdown from 'highlight.js/lib/languages/markdown';

hljs.registerLanguage('markdown', markdown);

export default {
  data() {
    return {
      code: ''
    };
  },
  computed: {
    highlightedCode() {
      if (!this.code) return '';
      return hljs.highlight('markdown', this.code).value;
    }
  }
};
</script>

<style scoped>
.markdown-editor {
  position: relative;
  width: 100%;
  height: 200px;
  border-radius: 5px;
  overflow: hidden;
}

.editor-input, .editor-highlight {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 15px;
  border: none;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-y: auto;
}

.editor-input {
  background: transparent;
  color: transparent;
  caret-color: #abb2bf;
  z-index: 1;
  resize: none;
}

.editor-highlight {
  background-color: #282c34;
  color: #abb2bf;
  z-index: 0;
  pointer-events: none;
}
</style>

关键细节说明

  1. 布局层叠:.markdown-editor设为相对定位,内部<textarea>和<pre>绝对定位,确保完全重叠
  2. 输入交互优化:<textarea>设为透明背景+透明文字,仅保留可见光标,同时通过z-index:1确保它在顶层接收用户输入
  3. 高亮层控制:<pre>添加pointer-events: none,避免干扰输入框的交互逻辑
  4. 性能优化:用computed属性生成高亮内容,仅在输入内容变化时重新计算,替代原有的监听事件,逻辑更简洁高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:48:34