我花了一些时间试图在文本区域上重叠pre标签,我试图构建某种文本编辑器。但是,以某种方式,pre标签未在其容器的左上方呈现,而是在中间呈现。没有保证金或填充物将其拉低,所以我没有主意。还有另外一件奇怪的事情,textarea的位置是:绝对的,但是它的容器仍在伸展到textarea的高度。

出于无奈,我从该库中复制了准确​​的代码:http://satya164.xyz/react-simple-code-editor/。但是,即使它是完全相同的代码,它仍然无法工作。

我当前的代码:



const codeEditor = document.getElementById("code-editor__textarea");
const codeRenderer = document.getElementById("code-editor__pre");

codeEditor.addEventListener("keyup", e => {
  codeRenderer.innerHTML = codeEditor.value;
});

*,
:after,
:before {
  box-sizing: inherit;
}

body {
  font-family: monospace;
  line-height: 1.5;
  margin: 0;
}

.code-editor {
  margin: 1.67em 0;
  max-height: 400px;
  overflow: auto;
}

.code-editor__container {
  background-color: #fafafa;
  box-sizing: border-box;
  font-size: 12px;
  font-variant-ligatures: common-ligatures;
  position: relative;
  text-align: left;
  white-space: pre-wrap;
  word-break: keep-all;
}

#code-editor__textarea,
#code-editor__pre {
  -webkit-font-smoothing: antialiased;
  display: inherit;
  font-family: inherit;
  font-size: inherit;
  font-style: inherit;
  font-variant-ligatures: inherit;
  font-weight: inherit;
  letter-spacing: inherit;
  line-height: inherit;
  padding: 10px;
  tab-size: inherit;
  text-indent: inherit;
  text-rendering: inherit;
  text-transform: inherit;
  white-space: inherit;
  word-break: inherit;
}

#code-editor__textarea {
  -webkit-text-fill-color: transparent;
  background: none;
  border: none;
  color: inherit;
  height: 100%;
  left: 0;
  outline: 0;
  overflow: hidden;
  position: absolute;
  resize: none;
  top: 0;
  width: 100%;
}

#code-editor__pre {
  margin: 0;
  pointer-events: none;
  position: relative;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Code Editor</title>
</head>

<body>
  <div class="code-editor">
    <div class="code-editor__container">
      <textarea id="code-editor__textarea" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea>
      <pre id="code-editor__pre" aria-hidden="true"><br></pre>
    </div>
  </div>
</body>

</html>

最佳答案

容器上的white-space: pre-wrap;导致此。

您已经使用绝对定位从流中删除了textarea-但是该行在它仍然存在之前和之后都中断了,并且由于您强制容器遵守它们,它们相应地将pre元素向下推。

(尽管将其删除也会使您的textarea的高度也变小,因为将其设置为容器的100%的高度。但是我想这对您来说是理想的效果?)

07-26 00:18
查看更多